Getting variables that from an array of scripts
Hello!
My scene has aliens that each has a lifetimer, when an alien is killed a manager script should register the life time of that alien. Right now i cant figure out how to get the independant scripts from the aliens in the manager script. I thought of using an array of scripts but the array is empty everytime i run the scene ...
This is the manager script:
using UnityEngine;
using System.Collections;
public class Manager : MonoBehaviour {
public AlienScript[] alienScripts;
public float[] lifeTimers;
void Start () {
alienScripts = GetComponents<AlienScript>();
}
}
Does anyone have tips on how to get the alien scripts and how to store their life timers in an array?
Thank you.
The GetComponents method only returns the AlienScript components attached to the $$anonymous$$anager game object.
Assu$$anonymous$$g that the AlienScript components are attached to seperate Alien game objects then the method would return an empty array. Is that correct?
The first step you then need to make is providing the $$anonymous$$anager with the game objects containing the AlienScript components.
I would suggest using a List, as it can more easily change size when you wish to add more aliens at runtime.
Edit: If you are just making a small test game. Then you can start by creating a number of Alien game objects. Disable them. Then drag all the game objects onto the AlienScripts field. You will then have them preloaded and no longer need to search for them at Start.
Answer by Placus_Brutus · Mar 01, 2016 at 08:18 AM
Add this above your "public AlienScript[] alienScripts" declaration:
private static Manager instance = null;
public static Manager managerController
{
get
{
if (instance == null)
{
instance = GameObject.Find("NameOfManagerObjectHere").GetComponent<Manager>();
}
return instance;
}
}
Then, create a new function:
public void SaveLifeTimers(float time)
{
// add to your lifeTimers array here!
}
Inside your Alien script now, create a new function:
void SaveTime()
{
float lifeTime; // Whatever your time is
Manager.managerController.SaveLifeTimers(lifeTime);
}
Hope it helps. If so, please mark it up as the answer. Good luck on your project!
Answer by Polymo · Feb 29, 2016 at 06:17 PM
alienScripts = FindObjectsOfType<AlienScript>();
but personally, i would make the manager a Singleton and let the alienscripts register themselves on creation and remove on Destroy.