In this example I have two fighters - left and right.
I’ve declared them like this :
public GameObject leftFighter;
public GameObject rightFighter;
And I assign them in the Start function
void Start (){
leftFighter = GameObject.FindWithTag ("Left Fighter");
rightFighter = GameObject.FindWithTag ("Right Fighter");
However in the rest of the code I have referenced components of these Game Objects.
if (leftFighter.MainCharStats.initiative >= rightFighter.MainCharStats.initiative)
When I use the script inside unity, though, it gives me this compiler error :
error CS1061: Type
‘UnityEngine.GameObject’ does not
contain a definition for MainCharStats’ and no extension
method `MainCharStats’ of type
UnityEngine.GameObject’ could be
found (are you missing a using
directive or an assembly reference?)
My guess is that for a script to work every variable including GameObjects must be defined, but in my case I don’t know how to assign a GameObject to a script without it giving those compiler errors.
How can this be fixed?
You need to use the GetComponent method to access components attached to your gameobjects.
This should work:
if (leftFighter.GetComponent<MainCharStats>().initiative >= rightFighter.GetComponent<MainCharStats>().initiative)
Save a reference to each MainCharStats the same as you have with the fighters, so…
MainCharStats LFighterStats;
MainCharStats RFighterStats;
void Start(){
LFighterStats = LeftFighter.getcomponent<MainCharStats>();
same for right here.
}
Then you can say
if(LFighterStats.initiative >= RFighterStats.initiative){
debug.log("We're in luck");
}
This should work… Hope it gets you started at least.