Grouping variables question
Right now I have a bunch of public stat variables in my AI script like:
public float SeeDistance;
public float SeeFOV;
public int health;
public bool alertState;
public bool isRifleEquipted;
public bool isPistolEquipted;
public bool isEngaging;
In the same script. If this AI spots an enemy AI I need to retrieve the stats of the enemy AI. Right now I just use something like:
GetComponent<AIScript>().SeeDistance
GetComponent<AIScript>().SeeFOV
GetComponent<AIScript>().health
GetComponent<AIScript>().alertState;
GetComponent<AIScript>().isRifleEquipted;
GetComponent<AIScript>().isPistolEquipted;
GetComponent<AIScript>().isEngaging;
It works fine but is there a way to retrieve all the stats with 1 GetComponent? Instead of calling GetComponent for each individual stat?
Answer by Jujo100 · Jan 13, 2016 at 12:09 AM
Hi,
Just do something like this:
AIScript aiScript = GetComponent<AIScript>();
aiScript.SeeDistance;
aiScript.SeeFOV
aiScript.health
aiScript.alertState;
aiScript.isRifleEquipted;
aiScript.isPistolEquipted;
aiScript.isEngaging;
Then you can just access those variables via aiScript instead of repeatedly calling GetComponent.
Hope that helps. J
Thanks that worked.
I know this looks better for sure.
Is this method better performance wise vs calling GetComponent on each individual variable?
It's definitely more efficient. Everytime you were calling GetComponent it was returning the same reference to the same AIScript object. It makes sense to save the reference once and use that to access the AIScript directly.
Regards, J