0
votes

Is there a good way to do this, i have copied my code below. This is my code so that the gameObjects patrol around a certain area of a map, i need a way so that when the enemies are spawned in to set the transform relative to the gameObject spawning the enemy in.

When I spawn my enemy in from the prefab, the enemy should patrol around the spawn point which spawned it in, however i have multiple points within the game which spawns the enemies in. The Patrol script has a transform public Transform moveSpots; which i assign the spawn point objects to.

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

public class Patrol0 : MonoBehaviour
{
    public float speed;
    public Transform moveSpots;
    private float waitTime;
    public float StartwaitTime;
    public float MinX;
    public float MaxX;
    public float MinY;
    public float MaxY;
    void start()
    {
        moveSpots = GetComponentInParent<Transform>();
        waitTime = StartwaitTime;
        moveSpots.position = new Vector2(Random.Range(MinX, MaxX), Random.Range(MinY, MaxX));
    }
    private void Update()
    {
        transform.position = Vector2.MoveTowards(transform.position, moveSpots.position, speed * Time.deltaTime);
        if (Vector2.Distance(transform.position, moveSpots.position) < 0.2f)
        {
            if (waitTime <= 0)
            {
                moveSpots.position = new Vector2(Random.Range(MinX, MaxX), Random.Range(MinY, MaxX));
                waitTime = StartwaitTime;
            }
            else
            {
                waitTime -= Time.deltaTime;
            }
        }
    }
}
1
Hi Adam. Welcome to Stackoverflow! It would be easier for us if you add your code to your question not the screenshot though. - Ali Kanat
Can you explain more about what you have and what do you want to get? - KamikyIT
gameObject.transform.parent will give you the parent transform for a child component. - RippStudwell
You mean like parentObject.transform.SetParent(childObject.transform);? - derHugo
It would be great if you add your code .. as text though - derHugo

1 Answers

1
votes

Assuming the object being spawned is also getting parented to the thing that is spawning, you could just replace all of your transform.position references with transform.localPosition. If not you can use Transform.TransformPoint() called from the spawner's transform.

Transform Spawner;

void start()
{
    moveSpots = GetComponentInParent<Transform>();
    waitTime = StartwaitTime;
    moveSpots.position = new Vector2(Random.Range(MinX, MaxX), Random.Range(MinY, MaxX));
    moveSpots.position = Spawner.TransformPoint(moveSpots.position);
}

This will take the local space moveSpots.position and convert it to world space relative to the Spawner.