Im kind of struggling calling a Function from my Enemy’s Script when attacking.
My current problem is not beeing able to reference the Script i need to call the Function on for the Enemy to get damaged. These Enemies are spawning over time while playing. How can this be achieved?
I’m not a pro at this, but here’s an example for how to use a list:
// Forgot Preprocessor stuff >:(
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
List<GameObject> pooledEnemyList;
public int pooledAmount;
void Start()
{
pooledEnemyList= new List<GameObject>();
for (int x = 0; x < pooledAmount; ++x)
{
GameObject obj = (GameObject)Instantiate(pooledObject);
obj.SetActive(false);
pooledEnemyList.Add(obj);
}
void FindEnemies()
{
foreach(GameObject obj in pooledEnemyList)
{
// Do something here like...
if(obj.active)
{
obj.GetComponent<SomethingYouWant>().SomeFunction();
}
}
}
Sorry for crappy formatting.
Jep @Metorphium, you are right, GameObject.Find would work but in a scene with a lot of objects it could heavily affect your performance. Then i would recommend to use the generic Lists approach. And its the even better solution if you want to damage ALL enemies.
The only thing you would have to do is to tell the enemy scripts to register themselves in some kind of EnemyManager script. And when you want to damage all of them just create a method inside your manager to do exactly that with iterating through the list of enemies and call a method like Damage(50.0f) or something.
Ill try to write a really short example for it:
EnemyManager.cs:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class EnemyManager : MonoBehaviour
{
public static EnemyManager instance = null;
List<Enemy> enemies;
void Awake()
{
if(instance == null)
{
instance = this;
}
else
{
Destroy(gameObject);
}
enemies = new List<Enemy>();
}
public void DamageAll(int damage)
{
foreach(Enemy e in enemies)
{
e.TakeDamage(damage);
}
}
public void RegisterEnemy(Enemy enemy)
{
enemies.Add(enemy);
}
}
Enemy.cs:
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour
{
int hp = 100;
void Start()
{
EnemyManager.instance.RegisterEnemy(this);
}
public void TakeDamage(int damage)
{
hp -= damage;
}
}
huh… so i dont need a list afterall if i just normally want to damage 1 Enemy… Well thats my bad, but Knowledge never is wrong. I may just keep the List for future capabilities.
I will read through that! Thank you!