- Home /
How to access the interface from the last component in the inspector
In the State Machine script I am trying to access the IState interface from PlayerAirborneState (the last compoenent in the inspector). Here's my code. https://rextester.com/EZPRPV52411 This however accesses the IState interface that is implemented in the top most component that implements IState. And I know this because I ran Debug.Log(airborne); and it outputted "Player (PlayerWalkState)" For debugging, I tried moving the airborne state component to the top and got the output "Player (PlayerAirborneState)". So I think Unity is just taking the first component that implements IState and using that.
How can I access the IState Interface from the PlayerAirborneState component without switching the order of components in the inspector?
Answer by UnityCoach · Oct 23, 2018 at 07:59 AM
To get the last component, you can simply do this.
IState[] states = GetComponents<IState>();
IState lastState = states[states.Length-1];
Although, looking at your code, you may assign the component itself, as IState
playerAirborneStateScript = GetComponent<PlayerAirborneState>();
airborne = playerAirborneStateScript as IState; // or
airborne = (IState) playerAirborneStateScript;
Thanks so much. Both solutions worked, but I chose to use yours because 1. I heard that using System.Linq; can be expensive, and 2. I understood it better.
Thanks for both responses guys!
Thank you. Understanding is key. One should never take an advice/solution that isn't understood.
System.Linq is actually very powerful, I use it quite often to collect items from lists that match some criteria. Although, I usually do this once, and if I had to do it at a high rate, I would certainly benchmark it with the Profiler.
Please accept the answer to close the question if you're happy with it.
Answer by ShadyProductions · Oct 23, 2018 at 07:01 AM
Something like this perhaps?
using System.Linq;
var states = GetComponents<IState>();
var airborneState = states.First(f => f.GetType().ToString().Contains("Airborne"));
The name
property of a component returns the name of the object, not the component's name. That said, you could do f.GetType().ToString().Contains("Airborne")
That makes sense, I've updated my answer.