Instantiate a prefab and assign it's values
I really need to assign the values of my prefab right after instantiating it. The source of my prefab is from assets, not from hierarchy. I do something like this: Code (csharp):
public GameObject boxPrefab;
public void InstantiateBox()
{
GameObject copy = (GameObject)Instantiate(boxPrefab, transform.position, Quaternion.identity);
copy.GetComponent<TestBoxScript> ().varToAssign = gameObject;
}
But the second line does not apply at all for some reason... The gameobject is instantiated but it's varToAssign does not change at all.
I really don't know how to approach my problem if this is not possible to do. And yes i tought of assigning the variable on Start() of my TestBoxScript but that's not gonna do what i want. I want my prefab to find it's belonger player, and if i did it from it's own script, it would never know which player it belongs to, if that makes sense. Also, this is not the original code i have, becouse i want my code to be private. But it's the same thing, it won't apply the second line in the function...
Just to make sure, the boxPrefab does have the TestBoxScript component attached to it? You don't get any NullReferenceExceptions on line 5?
Good to know! So since that is taken care of, do you do anything with the varToAssign on the Start/Enable of the TestBoxScript? This should technically be working fine, unless something else changes the variable in some other place.
Nope, and the variables are all null... I never made anything null in there through script so that means my code just didn't apply. Wierd... So friggen wierd...
Post your testBoxScript code so we can see if there is something to help we find out whats happening.
public GameObject varToAssign;
that's all the code there is in it
and the rest of the file with the "InstantiateBox" method?
Answer by RickyX · Jan 14, 2016 at 05:19 PM
Okay guys i've figured my problem out. Thanks for taking your time anyways. The thing was, instantiate picks anything you give it, it doesen't need to be a GameObject, i think atleast. the reference that i got from my item database for the prefab was a transform, that's why it didn't apply my lines.
Code (csharp):
ItemDB.GetComponent<ItemDatabase>().items[itmID].itemDragDropPrefab
itemDragDropPrefab was a transform so yeah, it took that and spawned it, and i couldn't assign anything becouse i did clone.GetComponent instead of clone.gameObject.GetComponent So it was my fault. And the real code i had is here: http://forum.unity3d.com/threads/instantiate-a-prefab-and-assign-its-values.379447/
Glad you figured it out! That's why sometimes you need to look at more code to solve the issue :)