- Home /
Referenced GameObject in inspector tracked different when set via code
I have a camera, with no parent, and a simple camera follow script. In that camera follow script I made a public GameObject field for the followTarget. If I drag an empty GameObject from the scene into that field in the inspector and enter play mode, all works as expected. I made a public method in that camera follow script, which takes a GameObject as an argument, and sets the followTarget to the passed in GameObject. When I do that, the camera follow script no longer works the same as when I assign it in the inspector, even if the object I pass in is the one that works when assigned in the inspector. Is there some difference between assigning a reference in the inspector compared to setting a value in the inspector? I'm using Unity version 2019.3.0f3
I've noticed that the camera follow also works if I drag an object into the inspector during runtime, and the icon for the correctly working gameobject is the black and white icon. But when I update the object to track via code, it is the blue icon like it's a prefab. Are prefab children somehow different than non prefab gameobjects?
Could you provide a snippet of what you've tried so far to give some context as to what might be going wrong?
I've arrived at a working solution, I think the issue is related to how Unity treats prefabs and children of prefabs in 2019.3.0f3. $$anonymous$$y Camera gameobject is not a prefab, there is another object in the scene we could call Object A, with children child a, child b, and child c. Object A is a prefab with those children, that is to say they are not nested prefabs. When I drag the prefab Object A into the scene and pass its children gameobjects to the camera's camera follow script via code, the camera always moves to the position of where the children were when the prefab was created. If I move the parent object or children around manually, the camera follow (running in Late Update) doesn't track to the new positions. However, if I instantiate the Object A and pass the instantiated children to the camera follow script it all works as expected. It's good that it should work when playing the game, it's just a hindrance when developing to have to drag a prefab into the scene, make changes and updates, then delete or disable that object and be required to instantiate a clone just for testing.
Your answer
Follow this Question
Related Questions
Assign video in inspector via script 0 Answers
Multiple Cars not working 1 Answer
Script forgets assigned Inspector variables 2 Answers
Distribute terrain in zones 3 Answers