- Home /
Clones of Prefab not behaving as Prefab
Dear coders
I have an enemy that I can instantiate several copies of :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using UnityEngine.AI;
public class GenerateEnemy : MonoBehaviour {
public GameObject enemy;
public float spawnTimer;
float x;
float y;
float z;
void Start (){
}
void Update ()
{
spawnTimer += Time.deltaTime;
createEnemy ();
x = Random.Range(-75, 75);
y = Random.Range (10, 10);
z = Random.Range(-75, 75);
}
public void createEnemy(){
if (spawnTimer > 10.0f) {
GameObject enemycopy = Instantiate<GameObject>(enemy);
enemycopy.transform.position = new Vector3 (x, y, z);
spawnTimer = 0.0f;
}
}
}
This is working fine.
I have a waypoint script that generates waypoints at a random position within the plane in a dynamic list. The original enemy prefab recognises this list and is able to recognise the waypoints.
Instantiated clones cannot recognise this list and therefore do not move.
In the enemy prefab, I have added a public gameobject of a waypoint generator. When the enemy clone is instantiated, this waypoint generator is visible in the inspector but the waypoints aren't generated and thus the enemy cannot move.
To further complicate matters, when I drag and drop the original enemy into the hierarchy, this is not an issue - the waypoint list is generated and works as is should independently for each enemy.
Could anyone make any suggestions as to how the above can be fixed? Do clones act differently to prefabs unless otherwise stated?
Thanks - I appreciate the above may be difficult to understand but I would be grateful for any help you could give me!
The problem is likely in your enemy or waypoint generation scripts. Somehow, the enemies are not being told about the waypoints that they have to move to. Without seeing those scripts there is no way anyone could help you with this.
Answer by ohkayem · Dec 30, 2017 at 06:40 PM
Waypoint Generation script is as follows :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using UnityEngine.AI;
public class WaypointList : MonoBehaviour {
public GameObject _gameObject;
public List<GameObject> _list = new List<GameObject>();
public float timer;
float x;
float y;
float z;
void Start (){
WaypointGenerate ();
}
void Update ()
{
List<GameObject> _list = new List<GameObject>();
timer += Time.deltaTime;
if (timer > 2.0f) {
WaypointGenerate();
timer = 0f;
}
x = Random.Range(-75, 75);
y = Random.Range (10, 10);
z = Random.Range(-75, 75);
}
void WaypointGenerate ()
{
GameObject clone = Instantiate (_gameObject) as GameObject;
clone.transform.position = new Vector3 (x,y,z);
_list.Add (clone);
}
}
This is attached to an empty gameobject.
The original enemy prefab that I drag into the scene view recognises this gameobject and the list generated by the empty gameobject. The instantiated enemy clones do not. Does this help?
Thanks!