The question is answered, right answer was accepted
Insert object to the list in the script in real-time.
Hello there, my problem is as follow:
I have a normal list. public List targets; I want two objects in this list, and then need to be able to update what object is in the index. So if i have two objects in the index like: Index 1: Object 1. Index 2: Object 2. Then i need to be able to update what object is in object 1 on the fly in the script, is this possible?
I tried using targets.insert(1, object3.transform), but it will keep adding objects to the list, not inserting it into just the index space.
Answer by sunrisepulp · Jan 26, 2018 at 03:29 AM
Okay so i kinda figured out how not to make it add forever, but the thing is, i cant get it to insert and replace the current object with the object i want in there. Thanks for taking a look at it, @F14M3THR0W3R
// Use this for initialization
void Start () {
targets.Add(puck.transform);
targets.Add(testobject.transform);
}
void FixedUpdate()
{
//Null.
if (targets.Count == 0)
return;
if (Input.GetKeyDown("space"))
{
//Trying to replace the object in the first index in the list with this object here.
if (!targets.Contains(replacementObj.transform))
targets.Insert(0, replacementObj.transform);
}
}
@sunrisepulp You could try using List.Remove() before actually inserting the object.
// Not tested
if (Input.Get$$anonymous$$eyDown("space")) {
if (!targets.Contains(replacementObj.transform)) {
targets.Remove (0);
targets.Insert (0, replacementObj.transform);
}
}
That worked! Thanks very much, feel so stupid now :)
Sorry but this makes no sense. "Remove" takes a parameter of the element type. $$anonymous$$aybe you meant to use RemoveAt which takes an index. However this also doesn't make much sense. If you want to replace an element in a list at a certain index, just replace it like this:
targets[0] = replacementObj.transform;
A list can be used exactly like an array. Of course you can only access (read / write) elements at indices which already exist.
@Bunny83 Sorry lol xD I haven't used list's much recently. What i meant to write was:
if (Input.Get$$anonymous$$eyDown("space")) {
if (!targets.Contains(replacementObj.transform)) {
targets.Remove (targets.Item(0));
targets.Insert (0, replacementObj.transform);
}
}
Excuse my ignorance, your solution would definitely work better, I didn't realise you could assign to List's like that, I need to stop using arrays xD