W
W
Workguy2021-02-27 22:42:39
Unity
Workguy, 2021-02-27 22:42:39

How to implement moving an object and creating a new one in unity?

I can create objects from "images" added to the project.
I can move objects.
And I want to combine these things: I'm trying to make it so that when an object enters the camera's field of view, a new object is created.
Here is my code:
1) Script to create object

public class test_script : MonoBehaviour
{
    public GameObject[] Objects;
    public GameObject mainObject;


    // Start is called before the first frame update
    void Start()
    {
        int rand = UnityEngine.Random.Range(0, Objects.Length - 1);
        mainObject = Objects[rand];
        Instantiate(mainObject, new Vector3 (0,0,0), mainObject.transform.rotation);
    }

    // Update is called once per frame
    void Update()
    {

    }
}

2) Script for the implementation of the movement. Also here I tried to create a new object if the current object's position reached its maximum.
Ps I added this script exactly to the object itself, so I do not specify a link to it.
public class moveScript : MonoBehaviour
{
    public GameObject[] Objects;
    public GameObject mainObject;
    public float movingSpeed = 5f;
    private Vector3 maxAheadPos = new Vector3(0,0,-10);
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.W)){
            transform.Translate(-Vector3.forward * movingSpeed * Time.deltaTime);
        }
        if (Input.GetKey(KeyCode.S)){
            transform.Translate(Vector3.forward * movingSpeed * Time.deltaTime);
        }

        if (transform.position == maxAheadPos) {
            int rand = Random.Range(0, Objects.Length - 1);
            mainObject = Objects[rand];
            Instantiate(mainObject, new Vector3 (0,0,0), mainObject.transform.rotation);
        }
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question