- Home /
Why do I get a context error when using GameObject.FindWithTag in Awake/Start function and GetComponent in a function?
Hello,
What I'm trying to do is this work from one script to another.
public void RaiseLevelsD ()
{
GameObject garbage = GameObject.Find("Garbag");
AnimationControl garbageScript = garbage.GetComponent();
GameObject tractor = GameObject.Find("Tractor");
AnimationControl tractorScript = tractor.GetComponent();
GameObject heart = GameObject.Find("Heart");
AnimationControl heartScript = heart.GetComponent();
garbage.active = true;
D++;
garbageScript.Level++;
if (X>0)
{
X++;
heartScript.Level++;
}
if (A>0)
{
tractorScript.Level ++;
A++;
}
if (F>0)
F++;
}
And this works just fine. But I understand that using "`GameObject.FindWithTag`" within a function, meaning everytime it hit that function, is pretty heavy on performance. So I tried to move:
GameObject factory = GameObject.FindWithTag("Factory");
AnimationControl factoryScript = factory.GetComponent<AnimationControl>();
to the Awake/Start functions, but I get this error: "error CS0103: The name 'factoryScript' does not exist in the current context."
Why? shouldn't it be available once I declare it on Awake or Start? Is there a way to do this?
Thank you!
Answer by whydoidoit · Jul 09, 2012 at 07:16 PM
You problem is that you need to make AnimationControl factoryScript a class level variable. But you would be much better off using singleton pattern.
In your Animation control:
public static AnimationControl Instance;
void Awake()
{
Instance = this;
}
Then in your RaiseLevelsE function:
AnimationControl.Instance.Level++;
But I am using the AnimationControl script on several objects, I'm updating the original question
Then in Awake put the component in a dictionary keyed off the name.
using System.Collections.Generic;
public static Dictionary<string, AnimationControl> controllers = new Dictionary<string, AnimationControl>();
void Awake()
{
controllers[name] = this;
}
void OnDestroy()
{
controllers.Remove(name);
}
Then AnimationControl.controllers["Garbag"].Level++;
Your answer
Follow this Question
Related Questions
StateMachineBehaviour get component on awake ?? 1 Answer
when loading a scene, the execution order is load->constructor->finishfunction->awake->start? 1 Answer
Object reference not set to an instance of an object 3 Answers
AddComponent passing variable before Start/Awake 5 Answers
FindGameObjectWithTag wont find in Start() or Awake() but will in Update() 1 Answer