How can you clear script data on an object

So i am using object pooling to spawn enemies, but once defeated I need them to clear the data from their script.
the code below is how I tried to do it, the first 4 things are nessicary,
but I the other 3 need to be cleared. I made them public to work here, but I would rather have them private.

void SpawnEnemy ()
    {
        GameObject enemy = transform.GetChild(0).gameObject;
        if (enemy != null)
        {
            enemy.transform.position = transform.position;
            enemy.GetComponent<EnemyScript>().path = path;
            enemy.GetComponent<EnemyScript>().healthbar = healthbar;
            enemy.GetComponent<EnemyScript>().health = enemyPrefab.GetComponent<EnemyScript>().health;
            enemy.GetComponent<EnemyScript>().gateScript = gateScript;
            enemy.GetComponent<EnemyScript>().nextPoint = enemyPrefab.GetComponent<EnemyScript>().nextPoint;
            enemy.GetComponent<EnemyScript>().existTime = enemyPrefab.GetComponent<EnemyScript>().existTime;
            enemy.GetComponent<EnemyScript>().startTime = enemyPrefab.GetComponent<EnemyScript>().startTime;
            enemy.SetActive(true);
            enemy.transform.SetSiblingIndex(enemiesToPool - 1);
        }
    }

Also, the last 3 need to be 0 when spawned, otherwise the enemies go crazy

Make a function in the EnemyScript class that does “all the things necessary” to reset an enemy.

If you like put it into an interface so that other scripts can implement it, and then the pooling mechanism can call it without knowing who is implementing it, perhaps something like IRecycleableEntity

Using Interfaces in Unity3D:

https://discussions.unity.com/t/797745/2

https://discussions.unity.com/t/807699/2

Check Youtube for other tutorials about interfaces and working in Unity3D. It’s a pretty powerful combination.

1 Like