- Home /
C# - can I cache a GameObject script component in another script?
I'm making some AI and I'm using this line a lot:
GetComponentInParent();
I know it's bad practice t call this too often, and I'd like to cache it if possible. There is a good chance if there are multiple game objects interacting at once, it may get called a dozen times.
Normally I cache components, however, I'm not sure how to do this with a script? or if it's even possible? I've tried this: Component parentScript = GetComponentInParent(); however, later on, when I try to get public variables like: parentScript.health, it doesn't pick it up.
Does anyone know if it's possible to cache a script component? (Or at the very least, link up variables some how?)
Answer by Landern · Nov 09, 2016 at 03:30 AM
You can get the component with the generic version, if you return a type component it will only have the Component type methods and properties/fields available. So.
//... snip
private AIGameObjectScript aigo; // cached version in script, just a field
// Start or where ever makes sense.
void SomeMethod()
{
aigo = GetComponentInParent<AIGameObjectScript>(); // The generic call that get the first AIGameObjectScript type component from the parent.
}
To repeat myself, getting the component type doesn't give the type you need(unless it does, but you stated it doesn't) You could cast it but you might miss the target.
well this doesn't entirely solve my problem. - But maybe you could suggest an alternative. Is there a way to store a reference to a variable, as a variable, within another script? for example, i've passed arguments with: void Something(string ref argument)
can i store a variable as a reference? like: 'private ref bool something' and then if I set 'something' it will change the referenced variable as well? or is this just a stupid question?
to put it short, I just need some way to cache references to variables in another script so my code isn't too clunky
Yes, that is the point of reference types(classes), unless you make a deep copy of the type it will be a reference, that is to say if you have a master/manager script keep references(pointers) to objects in other scripts with few exceptions anything you do in the master/manager script will affect the referenced objects, generally speaking you don't need to use the ref keyword either. As an example years ago i made a breakout clone, when each brick was instantiated in the level i had it register itself(read Add) it's own Brick instance to a $$anonymous$$anager script and a List, this allowed me to do various management on the stack or by references(IndexOf on the generic List) and left a lot of management to the $$anonymous$$anager singleton script. Like $$anonymous$$anager.DestroyBrick(this) from the OnCollision invocation on the Brick object and do various things to the score all in the manager script.