How to make objects appear in different positions?
Hello,
So I have a 3 x 3 gameboard with 9 items that I'm trying to place and after a certain time, they switch places. I've created a game objects array as well as a vector3 array to hold all possible positions. I then tried to set a timer to have the items swithc places after a certain time, but it doesn't work. My items are listed as item1, item2, etc. under a parent object called items. My script is on the parent item. Here's the code I've been trying:
using UnityEngine; using System.Collections;
public class Randomize : MonoBehaviour {
private Vector3[] positions;
public GameObject[] items;
int n;
float timer = 0;
// Use this for initialization
void Start () {
positions = new Vector3 [items.Length];
positions [0] = new Vector3 (-2, 3, 0);
positions [1] = new Vector3 (0.5f, 3, 0);
positions [2] = new Vector3 (3, 3, 0);
positions [3] = new Vector3 (-2, 0.5f, 0);
positions [4] = new Vector3 (0.5f, 0.5f, 0);
positions [5] = new Vector3 (3, 0.5f, 0);
positions [6] = new Vector3 (-2, 2, 0);
positions [7] = new Vector3 (0.5f, -2, 0);
positions [8] = new Vector3 (3, -2, 0);
items = GameObject.FindGameObjectsWithTag ("items");
for (int i = 0; i < items.Length; i++) {
positions [i] = items [i].transform.position;
}
}
// Update is called once per frame
void Update () {
var n = Random.Range (0, 8);
timer = Time.deltaTime;
if (timer > 1) {
positions [n] = items [n].transform.position;
}
}
}
Any suggestions on how to fix it and what I'm doing wrong?
Answer by corn · Jan 19, 2016 at 12:00 PM
Let's take a look at this Update method.
void Update () {
var n = Random.Range (0, 8);
timer = Time.deltaTime;
if (timer > 1) {
positions [n] = items [n].transform.position;
}
}
First of all, Time.deltaTime is the time it took to complete the last frame. It's not supposed to be greater than 1 at any given time.
What you meant to do was probably :
timer += Time.deltaTime;
Which would make way more sense : every frame, you add the elapsed time to your timer.
But then there's another mistake : positions [n] = items [n].transform.position;
This won't move your GameObject, this will only assign its current position to the nth entry of your positions array. If you want to move your GameObject, you should do the exact opposite : items [n].transform.position = positions [n];
You should probably fix that in Start too.
So what you should write is :
void Update ()
{
var n = Random.Range (0, 8);
timer += Time.deltaTime;
if (timer > 1)
{
items [n].transform.position = positions [n];
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612060622im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
setting up roommanager 0 Answers
How to get variables of a behavior tree with RAIN AI 0 Answers
NullReferenceException on getComponent 1 Answer
Playerprefs are not deleting when an apk is uninstalled? 0 Answers