I got a question. When i start my script. This code always wrong by attempt to index field '?' (a nil value)! i'm wanna to know why? Codes(The wrong place):
function findClosestComputer(Character) for i = 1,#AllComputers do local Computer local Distance = Player:DistanceFromCharacter(AllComputers[i].PrimaryPart.Position) local NextDistance = Player:DistanceFromCharacter(AllComputers[i+1].PrimaryPart.Position) --He said Here! attempt to index field '?' (a nil value) if Distance < NextDistance then Computer = AllComputers[i] print("1") else Computer = AllComputers[i+1] print("2") end end end
Thank you!
I also did it like that before but what happens is lets say you have 10 computers so the table is 10 index if the index comes to 10 like i = 10
then what is i
after AllComputers[i+1]
it is 11
so AllComputers[i+1]
it is trying to index a nil value because the table is only size 10.
What I was thinking is make the index start at the one before the last so if the size 10 the loop will end at 9.
function findClosestComputer(Character) for i = 1,#AllComputers - 1 do --Here I added that local Computer local Distance = Player:DistanceFromCharacter(AllComputers[i].PrimaryPart.Position) local NextDistance = Player:DistanceFromCharacter(AllComputers[i+1].PrimaryPart.Position) --He said Here! attempt to index field '?' (a nil value) if Distance < NextDistance then Computer = AllComputers[i] print("1") else Computer = AllComputers[i+1] print("2") end end end
Note!
That won't get the closest one since i
changes.
Read that code I gave earlyer then you can still change the names to your likingand so you get the latest closest distance.