float in for loop isnt changing
Hello, I tried creating a RTS prototype but im stuck with the formation of the units.A float (posadd) is after the loop changing back to 0 but in the forloop the float somehow starts again with the number of the forloop i did before(Console). Because of that the Units move even further down on every click...
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class UnitMovement : MonoBehaviour { public List<GameObject> units = new List<GameObject>(); Unit[] oldunits; bool clicked; public static RaycastHit hit; public static Vector3[] positions; private float posadd; void Start() { } void Update() { if (Input.GetMouseButtonDown(1)) //if mouse is clicked set bool to true { clicked = true; } if (clicked) { Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit); //ray to point i clicked oldunits = FindObjectsOfType<Unit>(); //get all units foreach (Unit uni in oldunits) //search if units are selected { if (uni.select == true) { units.Add(uni.gameObject); //put selected in list } } for (int i = 0; i < units.Count; ++i) //loop threw them { posadd += 2; //add 2 to distance units[i].GetComponent<Unit>().moveposition = new Vector3(hit.point.x + posadd, hit.point.y, hit.point.z); //add the distance to the position units[i].GetComponent<Unit>().move(); //give move command to unit (Navmesh) Debug.Log(posadd); } posadd = 0; //make distance 0 Debug.Log(posadd); clicked = false; //set clicked to false } } }
it would be very nice if someone could help me. first question here btw, but i hope i described my problem good egnoth...
Im soory but I dont know why the code got pushed together like this in the preview it was normally!
Answer by Heck134 · Nov 27, 2018 at 07:29 PM
Hi there @kirchler123,
This is an extremely strange issue and I can't see a cause myself; but as you currently have posadd as a global variable, you could try declaring it right before your forloop so that it is a new variable each time you hit the loop. That should guarantee that no value can be carried over. This is more of a Band-Aid fix, (and doesn't explain whats going on) but if you won't need to use posadd anywhere outside that loop it should be fine.
Relevant Changes;
bool clicked;
public static RaycastHit hit;
public static Vector3[] positions;
private float posadd; <------------------- Remove Me
if (clicked) {
DoTheUnitsStuff()
private float posadd;
for (int i = 0; i < units.Count; ++i) {
DoTheMovement()
}
posadd = 0; <------------------- Remove Me
}
Your answer
Follow this Question
Related Questions
SetSpeed float C# 1 Answer
Mathf.Round ? [C#] 2 Answers
Car is Flying instead of driving 1 Answer
subtracting from float in a user made function 0 Answers
I need to synchronize 2 float values of each character to another script, 0 Answers