Answer the question
In order to leave comments, you need to log in
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()
{
}
}
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 questionAsk a Question
731 491 924 answers to any question