- Home /
Prefab doesn't keep it's public variable when Instantiated?
So I'm trying to make a prefab for animated text and I want to Instantiate it by clicking a button. When I set the button up and run the game Unity says I'm missing a reference to the text object on the prefab. Why doesn't the text object stay on the animated text prefab? In fact once I turn the animated text object a prefab it losses it's reference to the text object, why?
I've tried to add a [Require(typeOf(Text))] on the script, but that does nothing either
Answer by tanoshimi · Feb 21, 2017 at 08:01 AM
Prefabs can't store references to instantiated objects in the scene hierarchy. What you should do is populate references to scene objects in the Start() method.
Thank you so much that worked for me! I just used the GameObject.Find() method in the Start() and it's working now!
Hi.. can you explain more and give some example? i'm having the same problem but i don't understand how to call the object in the start() method. Thank you very much.
like this.
public class ObjectA : $$anonymous$$onoBehaviour
{
public ObjectB objectB;
void Start()
{
objectB = FindObjectOfType<ObjectB>();
objectB.isFound = true;
}
}
and
public class ObjectB : $$anonymous$$onoBehaviour
{
public bool isFound;
}
of course if all you will ever have is a single ObjectB, then singleton or static management is better, like this.
public class ObjectB : $$anonymous$$onoBehaviour
{
public static ObjectB instance;
public bool isFound;
void Awake()
{
instance = this;
}
}
and
public class ObjectA : $$anonymous$$onoBehaviour
{
void Start()
{
ObjectB.instance.isFound = true;
}
}
Answer by samf1111 · Aug 20, 2020 at 09:59 PM
it worked for me when i used '[SerializeField]' instead of 'public'
Your answer
Follow this Question
Related Questions
Reinitialize prefab 0 Answers
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Problem to play animation in C# 5 Answers