- Home /
Getting Variables From An Arbitrary Component?
I am familiar with the basic way of getting components by
ASpecificComponent aSpecificComponent = (ASpecificComponent)transform.GetComponent("ASpecificComponent");
aSpecificComponent.anInt = 0;
However, now I have an array of components and I want to do something like:
compnentArray[1].anInt = 0;
or
Component aComponent = compnentArray[1];
aComponent.anInt = 0;
Trying to do that yields this error: Assets/Scripts/CharController.cs(111,38): error CS1061: Type UnityEngine.Component' does not contain a definition for
anInt' and no extension method anInt' of type
UnityEngine.Component' could be found (are you missing a using directive or an assembly reference?)
I suspect that it is not possible to do what I want to do but that there is something else that you do in a situation like this. By the way, all of the scripts in the array of components have a variable named anInt.
Does anyone know javascript? The problem is that the array is declared as just components, when it should be an array of whatever the script name is.
You don't show us the array declaration, so we are left to guess a bit on how you have things setup. If all the entries in the array are different instances of the same script, then @Owen Reynolds is right. You need to declare an array of the specific script. If the array is from different scripts, then you need to create a base class with 'anInt' and then derive all your other scripts from this base class. The array use the base class.
The array declaration is like this public Component[] componentArray;
and is filled by drag and drop. So your second supposition is correct, the array is from different scripts.
So let me see if I understand. I can create a class anywhere as
public class BaseScriptTyoe : $$anonymous$$onoBehaviour
that includes the variable. Then I can call the main class of a particular script
public class AParticularScripOne : BaseScriptType
Then I can create an array like
`public BaseScriptType[] componentArray;`
and it will take all of my particular scripts because of polymorphism?