- Home /
how do I move array objects to world coordinates?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class ArmyControls : MonoBehaviour { public TelegraphControl message;
public GameObject[] regimentsArray;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
// regimentsArray[0] move to A1
//condition
if (Input.GetKeyDown(KeyCode.Return) && message.reportText == ".-.-. break .-.----")
{
while(regimentsArray[0].transform.position.x != -8.5f)
{
float xValue = regimentsArray[0].transform.position.x;
float yValue = regimentsArray[0].transform.position.y;
if (regimentsArray[0].transform.position.x < -8.5f)
{
regimentsArray[0].transform.position = new Vector2(xValue + 1, yValue);
}
else if (regimentsArray[0].transform.position.x > -8.5f)
{
regimentsArray[0].transform.position = new Vector2(xValue - 1, yValue);
}
}
while (regimentsArray[0].transform.position.y != 4.5)
{
float xValue = regimentsArray[0].transform.position.x;
float yValue = regimentsArray[0].transform.position.y;
if (regimentsArray[0].transform.position.y < 4.5f)
{
regimentsArray[0].transform.position = new Vector2(xValue, yValue + 1);
}
else if (regimentsArray[0].transform.position.y > 4.5f)
{
regimentsArray[0].transform.position = new Vector2(xValue, yValue - 1);
}
}
}
}
}
When the condition is met, the game object does not move.
Comment
Best Answer
Answer by mchts · Mar 31, 2019 at 08:14 PM
Why do you even use while? Your script won't do anything when your position conditions not met anyway. So the short version of your code is:
if (Input.GetKeyDown(KeyCode.Return) && message.reportText == ".-.-. break .-.----")
{
if (regimentsArray[0].transform.position.x < -8.5f) {
regimentsArray[0].transform.Translate(Vector2.right); //translates one unit on x
} else if (regimentsArray[0].transform.position.x > -8.5f) {
regimentsArray[0].transform.Translate(Vector2.left); //translates minus one unit on x
}
if (regimentsArray[0].transform.position.y < 4.5f) {
regimentsArray[0].transform.Translate(Vector2.up);
} else if (regimentsArray[0].transform.position.y > 4.5f) {
regimentsArray[0].transform.Translate(Vector2.down);
}
}
And if this one does't work too, you better check whether you assigned the correct gameObject or not to your regimentsArray
Your answer
Follow this Question
Related Questions
Add Listeners to array of Buttons 2 Answers
Get an array of children from an existing array 1 Answer
Multiple Cars not working 1 Answer
How to read an int array using LitJson? 1 Answer
Distribute terrain in zones 3 Answers