I am making an NPC path tool in Unity and I have borrowed some functionality from this other post on stack overflow (How to make individual anchor points of bezier continuous or non-continuous).
I have not copied or repurposed anything that I could not have made myself, with the only exception being this line (at the bottom of the post), that unfortunately the entire program is dependent upon.
I understand that this is some kind of inline function declaration/definition, but I do not understand how it works. I think that the end result is a list of ControlPoint's being generated but I am not entirely sure.
I would not be that bothered but I am constantly getting an index out of bounds error from a loop in another class and the error code is pointing to this line. I am sure that I would be able to solve it if I could understand this line and deconstruct it. I suspect that it's some kind of C# specific ternary operator but I've never seen it before and although I've tried, I have no idea what to google or where to find the appropriate documentation to explain it.
So in essence I am asking for an explanation of the syntactic sugar on this specific line of code that this person has used so that I am able to deconstruct this line of code and fix the issue in my program.
Any help is appreciated, cheers!
(Original code sample):
public ControlPoint this[int i] { get { return points[(loop && i == points.Count) ? 0 : i]; } }
(ControlPoint is a seperate class used to define the properties and methods of an anchor point and the tangent points on a bezier curve)
(points is a list of ControlPoints)
(loop is a boolean variable that defines whether the path is closed or not)
Edit: Looks like the reason I didn't understand was not just because I'm not overly familar with ternary operators, it was because this person used an indexer/smart array, which is something I have never come across before. I'm going to remove that as I personally think it's overcomplicating things but here is the fully deconstructed indexer (without any ternary operators):
public ControlPoint this[int i]
{
get
{
if (loop && i == points.Count)
{
return points[0];
}
else
{
return points[i];
}
}
}
Thanks for everyone's help!
CodePudding user response:
Here's the verbose version:
if ((loop) && (i == points.Count))
{
return points[0];
}
else
{
return points[i];
}
It seems to be "looping" the array by returning the first element if you ask for the element after the last one. Meaning if the array has 10 elements (0 through 9) and you ask for element 10, it will "loop" and return the first element.
A "safer" alternative (orthogonal to your question) would be to use the modulo (%
) operator to enable "looping" (more commonly known as Circular Buffer ):
if (loop))
{
return points[i % points.Count];
}
else
{
return points[i];
}
or just
return points[loop ? (i % points.Count) : i];