I have this enemy named Simon, and it should do things when a variable in the script in MasterKey is updated. This is what happens when it’s not being played:
This is what happens when it’s being played:
The problem is, I can’t build it as it would remove the key behaviour. Please help, I have a short deadline.
..
using UnityEngine.AI
public class SimonBehaviour : MonoBehaviour
{
public GameObject simon;
public KeyBehaviour _keyBehaviour;
private void Awake() {
_keyBehaviour = GetComponent<KeyBehaviour>();
}
}
EDIT: It doesn’t remove the script when I have the SimonBehaviour script turned off.
Why do you do GetComponent when you already have that reference assigned in the Inspector?
Most probably the GameObject that runs the Simon script doesn‘t have a KeyBehaviour component, therefore GetComponent returns null when you enter play mode. If the KeyBehaviour component is on a different game object then you first need a reference to that GameObject. Or simply don‘t call GetComponent, you already have this reference assigned in the Inspector.
In general this horrible dangerous ninja code pattern needs to be abandoned, except in the rare cases where it is the only solution, which is almost NEVER the case.
Keep in mind that using GetComponent() and its kin (in Children, in Parent, plural, etc) to try and tease out Components at runtime is definitely deep into super-duper-uber-crazy-Ninja advanced stuff.
This sort of coding is to be avoided at all costs unless you know exactly what you are doing.
If you run into an issue with any of these calls, start with the documentation to understand why.
There is a clear set of extremely-well-defined conditions required for each of these calls to work, as well as definitions of what will and will not be returned.
In the case of collections of Components, the order will NEVER be guaranteed, even if you happen to notice it is always in a particular order on your machine.
It is ALWAYS better to go The Unity Way™ and make dedicated public fields and drag in the references you want.
In general, DO NOT use Find-like or GetComponent/AddComponent-like methods unless there truly is no other way, eg, dynamic runtime discovery of arbitrary objects. These mechanisms are for extremely-advanced use ONLY. If something is built into your scene or prefab, make a script and drag the reference(s) in. That will let you experience the highest rate of The Unity Way™ success of accessing things in your game.