Unity instantiate after destruction - c#

How do I instantiate multiple instances of the FloatingText that destroys itself in 1 second?
I'm using this script to instantiate a floating text.
if (Input.GetKey("w")) {
GameObject floatingText = Instantiate(floatingTextPrefab, position, Quaternion.identity, transform);
}
In the FloatingTextPrefab, I added a component script called DestroyTimer. So tht text disappears in 1 second.
void Start()
{
Destroy(gameObject, 1f);
}
Now whenever I press the key, it says
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Why is it deleting the prefab, instead of itself as an instance?
I'm trying to follow this but he doesn't encounter the same problem.
https://youtu.be/LjNsDVYXfrk?t=364

If your prefab is also in the 3D scene, it will execute the destroy itself whenever it's visible.
It means that your prefab already destroy itself before you pressing "W".
Below is the suggested way to do it.
if (Input.GetKey("w"))
{
GameObject floatingText = Instantiate(floatingTextPrefab, position, Quaternion.identity, transform);
Destroy(floatingText, 1f);
}
and please remove the destroy function within your prefab:
void Start()
{
//Destroy(gameObject, 1f);
}
Edit:
If you want to use your original setup.
Two options:
option 1: saving it as prefab, and assign the prefab from asset folder.
option 2: always disabling the prefab by default, only enabling the instantiated object.

I think I figured it out. I need to delete the FloatingTextPrefab in the scene, only leave it in the assets. And in the components menu associate the one from Assets instead of the one in the scene.

Related

cant make my gameobjects change position after collision [duplicate]

First, I know that this question has been asked a lot, but I cant find a solution, so mi problem is, Im making an educational game, and I have a vein and the blood flow (with many box colliders) and a single blood cell (also with a box collider) however i want the cell to destroy when it reaches the wall collider, but it doesn't it just stays there, here is the project!
http://tinypic.com/r/10706es/9
(cant upload images because of my reputation, sorry)
The collider where I want to destroy my cell is the pink collider, however when it touches it it just does nothing, here's my script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class collision : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void OnCollisionEnter(Collision col)
{
print("hihi");
if (col.gameObject.tag == "Collider")
{
Destroy(gameObject);
}
}
}
Also, here is the AddForce script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AddForce : MonoBehaviour {
public float thrust;
public Rigidbody rb;
private Vector3 up;
private bool move;
void Start()
{
rb = GetComponent<Rigidbody>();
up = new Vector3(0, 1, 0);
move = false;
}
void FixedUpdate()
{
if (Input.GetKey("space"))
{
if (rb.velocity.magnitude < 5)
rb.AddForce(up * thrust);
move = true;
}
else
{
if (move == true)
rb.velocity = new Vector3(0, -0.5F, 0);
}
}
}
thanks for your help guys! :D
It can be several things, whether you are using OnTriggerEnter or OnCollisionEnter:
Missing RigidBody (the most common). At least one of the GameObjects involved needs to have a RigidBody. (check if at least one of them have a RigidBody attached and, if you are using OnCollisionEnter, does not have the "Is Kinematic" checked). See the below collision matrix for more information.
Missing tag. The GameObject from collision does not have a "Collider" tag (try to remove the if statement to test it) (to compare tags, use collider.gameObject.CompareTag("Collider"), it has a better performance)
Undetectable collision. The physics Layer Collision Matrix is set to not detect collision between the layers the objects are (enter Edit > Project > Phisics and check if the encounter of the layer of both GameObjects are checked inside Layer Collision Matrix)
Wrong Collider configuration. one or both of the GameObjects have a small/wrong placed or absent Collider (check if they both have a Collider component and if their size are correct)
If it's working, you should be able to press play and drag one GameObject into the other one and your Debug.Log will appear.
As an advice, use tag names that better describe the group of GameObjects that will be part of it, like "RedCells" or "WhiteCells". It'll be easier to configure the Layer Collision Matrix and improve the performance of your game.
Another advice: for colliders that just destroys another GameObject (don't react, like bump or actually collide) I use triggers. That way, the collision between them will not alter anything in the remaining GameObject (like direction/velocity/etc). To do that, check the Is Trigger in the Collider and use OnTriggerEnter instead of OnCollisionEnter.
Source
some times you added Nav Mesh Agent component to your game object ( to auto route operation in strategic game and ...).
in this case, this game object does not attend to collider.
So, if you really need this Nav Mesh Agent, you should add Nav Mesh Obstacle to other fixed game object and also add Nav Mesh Agent to other movable game object.
I have a few followup questions which might lead to a solution.
First, does the object holding your 'collision' script have a rigidbody and a collider on it?
Second, does the wall have both a rigidbody and collider?
Usually if those conditions are met, then collisions will work.
A couple other things that could be the problem:
Check if you have istrigger checked for either object and make sure it is unchecked.
Check and make sure the rigidbodies on both are non-kinematic.
I've finally fixed it, I dont really know if this was the problem, but i just removed the rigidbody from the parent of the wall and it started working!, I dont know what the rigidbody did, but just with that the problem was fixed, thank you all for your help! :D
Ensure the following things are considered in your code,
All gameobject should contain collider attached and the player
gameobject should contain the rigidbody component in it.
The collider size should change to the width and height of the
component instead of default (1,1) values.

The ball does not come out of the barrel of the rifle according to where the player is moving

The ball does not come out of the barrel of the rifle according to where the player is moving
`void Update () {
if (Input.GetKey (KeyCode.C))
{
Instantiate (bool_gun.transform, bool_.transform.position, Quaternion.identity);
}`
In case you're trying to instantiate a new bullet coming out of a riffle that the player is carrying, you'll have to instantiate the prefab at the position where the riffle is currently located, NOT the position that the prefab has stored, which is something that does not change at runtime, but is just statically set in your prefab
void Update () {
if (Input.GetKey (KeyCode.C))
{
Instantiate (bool_gun_PREFAB, PLAYER_(RIFFLE)_POSITION, Quaternion.LookDirection(PLAYER_(RIFFLE)_FORWARD));
}
If you can actually put a question-mark in your question and clearly state what you are trying to achieve, how you do it, what goes wrong and what you have tried, we can maybe help you further
Not much information to work with, but, if I were writing this I would create a empty game object called bullet spawn, make it a child of the rifle, adjust it to the end of the barrel, and set that as your transform.position.

Moving a GameObject using tags not working Unity

I know this is quite the noob question, but whatever, there's only one way to learn.
I've created an empty GameObject in Unity, attached a script that is supposed to move a cube(my player) and gave my cube the tag "Player". After creating the cube, I was hoping to be able to move the cube without having to put the script on the cube itself. When the script is on the cube, it moves without a problem (I know this is how it probably should be done, but for trying to learn new things I wanted to do it this way).
Player Controller script
Cube properties
After failing to find the answer through Google, any insight at all is greatly appreciated!
Thank you
Update!
Here's the code as text now, since it was asked for.
public class GameCoreController : MonoBehaviour {
private GameObject PlayerMove;
public Rigidbody rb;
void Start ()
{
PlayerMove = GameObject.FindGameObjectWithTag("Player");
rb = GetComponent<Rigidbody>();
}
void Update()
{
// character movement
if (Input.GetKey(KeyCode.W))
{
PlayerMove.transform.Translate(0, 0, 0.25f);
}
if (Input.GetKey(KeyCode.S))
{
PlayerMove.transform.Translate(0, 0, -0.25f);
}
if (Input.GetKey(KeyCode.A))
{
PlayerMove.transform.Translate(-0.25f, 0, 0);
}
if (Input.GetKey(KeyCode.D))
{
PlayerMove.transform.Translate(0.25f, 0, -0);
}
}
I've updated the code from before to include PlayerMove.transform.Translate but I still have the same issue with the cube note moving. I've also included screenshots of my scene with the cube and the GameCoreController; the empty GameObject holding the script that is supposed to control the cube.
Thanks again for the help guys.
Update 2!
After deleting the cube and re-insert it into the scene it now moves. Thanks for the help everyone.
The reason that the cube won't move because in your code you didn't move its transform but you move the transform of the gameobject that you attached this script to.
transform.Translate move the transform of the gameobject that this script attach to. So if you want to move the cube, all you need to do is change from transform.Translate to PlayerMove.transform.Translate which will move the transform of PlayerMove gameobject which is your cube with "Player" tag on it
^ All of the above. Plus, in the screenshot, your rigidbody is not set to "is kinomatic". This means that physics will still be applied to it (like gravity). Rule of thumb: If you have a moving object where collision is important, it will need a rigidbody and a collider. If the object is not moved with physics commands (eg rigidbody.AddForce()) but rather manipulating the transform as you are, set the rigidbody "isKinomatic" property to true.

Unity/C# Trigger Making something else dissapear

Im trying to make it so that when i trigger a trigger in Unity, it doesnt remove the trigger, but it does remove what the trigger is attached to. but i cant seem to figure out how to do it.
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("pickup"))
{
audio.Play(); //Play it
other.gameObject.SetActive(false);
count = count + 1;
SetCountText();
}
}
This is an example of what im trying to do, but imagine it trying to set something else to inactive.
When you deactivate the game object, the attached collider will be deactivated too. If you want to deactivate a game object and let the collider exist you need to distinct between those two, i.e. have two game objects: one just for the collider and one for the actual object. now you can remove the actual object while the collider can continue to function.
The implementation depends on how you are handling the trigger.
case 1:
OnTriggerEnter is written in a script attached to the game object which static collider (ground) is attached to.
static collider is a collider without a rigidbody.
add a child to this game object and put the visuals in it (i.e. renderer or audio source).
add public GameObject Child; to the script.
set the reference of the child via unity inspector window.
deactivate the child instead of collider's gameobject in OnTriggerEnter method: Child.SetActive(false);
case 2:
OnTriggerEnter is written in a script attached to another game object which also has a dynamic collider (ball) and a rigidbody.
dynamic collider is a collider with a rigidbody.
add a child to the game object which the static collider is attached to
add a script to the game object (MyScript)
add public GameObject Child; to the script.
set the reference of the child via unity inspector window.
deactivate the child instead of collider's gameobject in OnTriggerEnter method: (other as MyScript).Child.SetActive(false);
When you deactivate an object with gameObject.SetActive(false); you automatically deactivate every component on you object (Renderer, Triggers, Scripts, ...)
There is two options to achieve what you want to do:
Use another object as a trigger (a Plane or a Cube and deactivate your object from this new object)
Or as suggested by #madjlzz you can deactivate your Renderer and RigidBody

Unity attaching GameObjects to scripts as a class

About a month into making my first game, I have realized that I am very confused when it comes to attaching gameobjects as classes to another game object's script. That's a mouthful so here's my issue.
My Game.cs attached to Game (gameobject) has
public Player player;
My Player.cs is attached to a Player (gameobject) prefab
Why can I drag a Player gameobject, that has a player script, into the Game gameobject's "player" field? How does that make sense? It should be
public GameObject player;
Then I would drag my prefab gameobject "Player".
The reason why this confuses me is, If i Instantiate "player", am I instantiating a gameobject? It seems not, because I cannot do this:
GameObject newPlayer = Instantiate(player, new Vector3(1,1,1), Quaternion.identity) as GameObject;
newPlayer.transform.SetParent(GameObject.Find("Level"));
If I do I will get the error the newPlayer is null.
A script is actually a Component object like any other object (most of the time).
It is technically not too easy to drag a Component object from an inspector onto another slot in another inspector. Probably thats why they made this "shorthand", when you can drag the actual GameObject instead from the hierarchy.
If the dragged GameObject has a matching component to a slot, it counts as you have dragged the Component itself.
You cannot instantiate a script Component using Object.Instantiate, you'll always instantiate a GameObject this way, see the docs. If you need the script, simply get the component from the brand new instance.
It can be confusing indeed, I personally prefer naming convention something like:
public GameObject playerObject;
public Player player;
Unity. by default, will cast any gameobject into the possible component, for example, if you have a Transform in your script and pass a gameobject (as a lot of tutorials do), it will automatically cast to the transform of given gameobject.
The main problem with that is simply that if you try to attach an object without Player script, it will probably crash in one way or another if you don't check the value.
Anyway, while you are working with your own scene and are sure the player gameobject has the necessary script, it won't be a problem in any way
Oh, about the last part, attaching components is common for already instantiated objects, to instantiate from a component you should get the parent game object of that script, and it would not make sense as you could easily attach the prefab directly
I don't remember now exactly how, sorry

Categories