I have an airplane and a component on it PlayerAirplane. PlayerAirplane is inherited from base class Airplane. On another game object I have another script that is trying to access the airplane component on airplane game object.
To access that component I would like to use its base class like:
airplaneComponent = (Airplane)airplane.GetComponent(“Airplane”);
I wonder will this work ? And if not how to make it to work ?
Airplane component is not directly located on airplane game object but its inherited class PlayerAirplane is.
airplaneComponent = (PlayerAirplane)airplane.GetComponent("Airplane"); //Unsafe (May cause cast errors)
//or
airplaneComponent = (airplane.GetComponent("Airplane") as PlayerAirplane);
if (airplaneComponent == null)
Return;
//or
airplaneComponent = (Airplane)airplane.GetComponent("Airplane");
if (airplaneComponent is PlayerAirplane)
{
//Do stuff
}
Yea, but what if airplane game object has no Airplane component on it but only PlayerAirplane. Will these line of code return null ?
I just saw, you used:
airplane.GetComponent(“Airplane”) as PlayerAirplane
but I want the opposite way and also I don’t want to use inherited class in quotes. In the other script that is accessing it has only defined:
Airplane airplaneComponent;
Ah, I see, I think (but not sure) that you’re able to use if (var.GetType().BaseType() == typeof(type)) otherwise use not equal with the same samples above;
airplaneComponent = (Airplane)airplane.GetComponent("Airplane");
if (!(airplaneComponent is PlayerAirplane))
{
//Do stuff
}
Edit:
You could also use an additional class to differ between them (may make it easier later);
Abstract Class Airplane : MonoBehavior { }
Class PlayerAirplane : Airplane { }
Class ComputerAirplane : Airplane { }