How do declare a nonspecific class to be defined later.
I've got two different controller scripts, one for AI and one for human players. When one player attacks the other, they need to grab the relevant script from the enemy they are attacking. To do this they access another script on the enemy that checks if they have been assigned as AI, this is that script.
public class myInfo : MonoBehaviour {
public int PlayerID;
public bool AmAI = false;
public Component myController;
void Awake () {
if (AmAI)
{ myController = GetComponent<AIController>(); }
else
{ myController = GetComponent<PlayerController>(); }
}
}
I've declared a Component called myController to later be changed depending on whether or not the player is an AI. The problem is, when I assign this to another variable and try to use functions from either script, the code tells me that Component doesn't contain definitions for those functions. Example:
targetAttributes = tarHit.collider.GetComponent<myInfo>().myController;
targetAttributes.playerBlocking == false
I get the message-
"'Component' does not contain a definition for 'playerBlocking' and no extension method 'playerBlocking' accepting a first argument of type 'Component' could be found (are you missing a using directive or an assembly reference?) Assembly-CSharp "
So how do I declare and reference an empty variable that is later defined, that will contain the right definitions as the assigned script?.
Answer by hexagonius · Jan 18, 2016 at 08:43 PM
You need to cast the component into its actual type. Use if (mycontroller is PlayerController)
for checking. Use mycontroller as PlayerController
for the cast. with "as" you'll get a NullReferenceException I'd the cast failed.
Sidenote: calling the base class 'Component' might not be a good idea, because the term is already used for all the components in Unity... might be confusing.
Your answer
Follow this Question
Related Questions
How to correctly handle NullReferenceException when using GetComponent<>? 1 Answer
Game Manager can't decide what the instance of the object is despite just making an instance of it 1 Answer
Get Component isn't working too well 1 Answer
UNET Commands calling advice. Calling Commands from CHILD object 1 Answer
Problem Destroying Component 0 Answers