1
\$\begingroup\$

I have two OnValidate() functions in two scripts, one attached to the Enemy (EnemyScript) game object and the other to the Enemies(EnemiesScript) game object.

In OnValidate() in EnemyScript I have the following:

    void PrepareEnemyType(EnemyType enType) {

    // by default hasHibernated = false
    if (!hasHibernated) {
        if (enType == EnemyType.Green) {
            gameObject.GetComponent<SpriteRenderer> ().sprite = Resources.Load<Sprite> ("Sprites/greenEnemy");

        } 
        else if (enType == EnemyType.Red) {
            gameObject.GetComponent<SpriteRenderer> ().sprite = Resources.Load<Sprite> ("Sprites/redEnemy");

        }
    }

    else if (hasHibernated) {
            gameObject.GetComponent<SpriteRenderer> ().sprite = Resources.Load<Sprite> ("Sprites/greyEnemy");

    }
}

In OnValidate() in EnemiesScript I have the following:

for (int i = 0; i < enemies.Length; i++) {
        if (!enemies [i]. hasHibernated) {
            enemies[i]. hasHibernated = true;

        }
    }

based on the above all the enemies should change sprite to greyEnemy sprite, but that doesn't happen. Before I run the application all of them change to greyEnemy sprite initially, then after I run the application some of them change back to their original sprites, and when I stop running the application they sprites remain the same as when the application was running (different sprites). At this point, the only time that they all become grey again is when I make some other edit to either one of the scripts and save it. Then the above transition repeats. I suspect there could be some conflict with the two OnValidate() functions, not certain though. How can I resolve this?

\$\endgroup\$
  • \$\begingroup\$ else if (hasHibernated) can be simplified to just else, the variable is a boolean so it only has two values and you already checked one of them. \$\endgroup\$ – Draco18s no longer trusts SE Jul 14 '17 at 15:32
1
\$\begingroup\$

From documentation:

This function is called when the script is loaded or a value is changed in the inspector (Called in the editor only).

OnValidate doesn't get called unless you manually set values in the inspector.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.