- Home /
How do I reassign a public variable on an instantiated object?
New Unity user here. I'm network instantiating a character "MyCharacter", with a number of public variables. One of them is a reference to another game object - - specifically, I want MyCharacter to follow SomeGuy, so I do this:
public gameObject followMe;
And I drag the SomeGuy prefab into the followMe field on the MyCharacter script.
Problem is, when I instance MyCharacter, he now thinks SomeGuy is at 0,0,0 - when in fact SomeGuy is flying around up high.
If, while the game engine is running, I select MyCharacter, I can then re-drag SomeGuy into the followMe field, and everything works great!
After some reading, it looks to me like this is due to serialization of the prefab, but I have no idea how to fix this. I've also read a thing or two about fixing this with the GameObject.FindWithTag trick, where the prefab is in a special "Resources" folder - but again, I can't figure out how to make this work.
Halp? :)
a clever friend provided the answer: in the instantiation script, I add this:
$$anonymous$$yCharacterControllerScript mccs;
mccs = $$anonymous$$yCharacter.gameObject.GetComponent<$$anonymous$$yCharacterControllerScript> ();
mccs.follow$$anonymous$$e = GameObject.Find ("SomeGuy");
works like a charm. Whew!
Answer by KellyThomas · Dec 29, 2013 at 07:01 AM
If you have only one SomeGuy (and he is named "SomeGuy") then you can place this line in your MyCharacter.Start() method:
followMe = GameObject.Find("SomeGuy");
Your answer