- Home /
How to store a prefab in a variable
So I posted yesterday because my prefab wasn't getting destroyed, Turns out the object was null!
public void drop() {
//creates a bobber
GameObject bobber = Instantiate <GameObject>(bobberPrefab, new Vector3(-0.999f, 0.168f, 0), new Quaternion(0f, 0f, 0f, 0f));
}
the problem lies here, I am trying to destroy "bobber", And it doesn't store the gameobject, So can someone tell me how to do it?
.bobber is an empty public gameobject
.bobberPrefab contains the prefab
GameObject bobber = Instantiate (bobberPrefab, new Vector3(-0.999f, 0.168f, 0), new Quaternion(0f, 0f, 0f, 0f)) as GameObject;
try this
Answer by Iarus · Jan 04, 2020 at 09:48 PM
When the drop()
method is called, is the bobberPrefab
variable null
or otherwise invalid?
After the Instantiate()
method is called, is the bobber
variable null
? Maybe Instantiate()
failed for some reasons.
I can't see your code where you're destroying the bobber, but I'll assume that it's in an other method.
Your bobber
variable is a reference to the GameObject that Unity gave you after calling Instantiate()
. It's also a local variable, meaning that at the end of the drop()
method, all local variables will be deleted. Since bobber
is a GameObject created through Instantiate, Unity will keep track of it and it won't be destroyed at the end of drop()
, but your way of talking to it will lost.
You should store your newly created object in a variable with a higher scope, in a class member variable.
class MyClass : MonoBehavior
{
[SerializeField] private GameObject bobberPrefeb;
private GameObject bobber;
public void Drop()
{
bobber = Instantiate(........);
}
public void KillBobber()
{
Destroy(bobber);
}
}
I don't know if this code is supposed to manage only one or many bobbers.
If it's only one, either make sure
Drop()
cannot be called more then onceif (iWantToCreateABobber && bobber == null) { Drop(); }
, or the method does nothing if the bobber already existsif (bobber != null) { return; }
. Or destroy the previous object before creating a new one.If it's many, then replace the
bobber
member variable by an array, a list or some other type of collection and adjust the code to store it, then find a way of destroying the correct one.