mardi 7 mai 2019

Prefab enemy all walk in same random path

I have a script on an enemy that walks randomly inside a square. I get a random point from that square and moves the enemy towards that random generated point. The problem is that whan instantiating multiple enemies they all run on the same script and uses the same random generated point so they all ends up walking in the same direction.

I think unity only instantiates copies of the prefab not the script so that all prefabs uses the same script.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WanderSquare : MonoBehaviour
{
    public Renderer square;
    Vector3 size;
    public int directionChangeInterval;
    static Vector3 direction;
    public float speed;

    void Start()
    {
        size = square.bounds.size;

        StartCoroutine(NewHeading());
    }


    Vector3 NewHeadingRoutine()
    {
        Vector3 position = new Vector3(Random.Range(-size.x/2, size.x/2), 0.3f, Random.Range(-size.z/2, size.z/2));

        return position;
    }
    IEnumerator NewHeading()
    {
        while (true)
        {
            direction=NewHeadingRoutine();
            yield return new WaitForSeconds(directionChangeInterval);
        }
    }
    private void Update()
    {
        transform.position = Vector3.MoveTowards(transform.position,direction,speed/100);


    }
}




Aucun commentaire:

Enregistrer un commentaire