Hi, I have a peculiar problem.
My character game object has a AbilityHandler script. For abilities I create empty GameObjects, add the ability script and then save them as prefabs. Then I drag the ability prefab into the AbilityHandler of the character prefab.
The AbilityHandler checks during update for hotkeys and calls the OnActivate method of the ability. If this returns false the ability isn’t done yet (because it’s waiting for a click). The OnActivate method also gets the reference to the character gameObject. But then in the update method of the Teleport script the reference to the character is suddenly null. But here’s the strange thing: If the OnClick handler is called, the caster reference is no longer null. I added a Debug.Log to the Caster Property to see if it was being accessed, but it’s only set once, during the OnActivation method.
Why is the Caster Property null in the update method and then suddenly no longer null in the OnClick handler, if the reference hasn’t been changed?!
public class AbilityHandler : MonoBehaviour {
// I drag a list of prefabs containing the Ability Script into the field via inspector
public List<Ability> Abilities;
public bool OnLeftClickUp(ClickLocation click) {
if (activeAbility == null || !activeAbility.OnLeftClickUp(click)) return false;
activeAbility = null;
return true;
}
private void Update() {
if (activeAbility != null) return;
Abilities.ForEach(ability => {
if (Input.GetKey(ability.Hotkey)) {
activeAbility = ability;
}
});
// Here I give my teleport script a reference to the caster game object
if (activeAbility == null || !activeAbility.OnActivation(gameObject)) return;
activeAbility = null;
}
}
public class Teleport : Ability {
public GameObject Caster {
get { return casterInternal; }
set {
// I'm logging access to the Caster property
Debug.Log("Setting: " + value);
casterInternal = value;
}
}
private GameObject casterInternal;
public override bool OnActivation(GameObject cas) {
Debug.Log("OnActivation");
// We are setting the caster to a non-null value;
Caster = cas;
return false;
}
public void Update() {
if (Caster == null) return;
Debug.Log("this statement will never be reached since the caster is null");
}
public override bool OnLeftClickUp(ClickLocation click) {
if (Caster == null) return;
Debug.Log("On click the Caster is suddenly no longer null");
return true;
}
}
Here’s the console output: