how to allign an existing object's position onto a a separate object's position in an array

Hi, this is my first time posting here,

I wanted to make a small test project where i move a character along a grid that was that is made from instantiated points of a multidimensional array
this is how the grid looks:

And here’s the code:

public class GridManager : MonoBehaviour
{
    [SerializeField] Transform pointPrefab;
    [SerializeField] Transform playerPrefab;
    float scale = 2f;
    int gridScaleX = 4;
    int gridScaleY = 2;
    Transform point;
    Transform startPoint;
    Vector3 position;
    Transform[,] gridPoints;

    private void Awake()
    {
        MakeGrid(gridScaleX, gridScaleY);
    }


    public void MakeGrid(int x, int y)
    {
        gridPoints = new Transform[x , y];

        for (int i = 0; i <= gridPoints.GetLength(0); i++)
        {
            for (int j = 0; j <= gridPoints.GetLength(1); j++)
            {
                point = Instantiate(pointPrefab);
                point.localPosition = new Vector3(i * scale, 0, j * scale);
            }
        }
        startPoint = Instantiate(playerPrefab);

        startPoint.localPosition = new Vector3(gridPoints[1, 1].position.x, 0, gridPoints[1, 1].position.z);

    }
}

I wanted to place a placeholder player object (playerPrefab) to one of these spaces, (let’s say at gridPoints[1,1]) but any time I try to assign the transform position of one of the points, it always instantiates the player prefab at its origin point, x:0, y:0, z:0 (the sphere representing the visuals is higher because it is a child attached to an empty game object, which is at 0, 0, 0),

intead of the location of the point, how would I make it so that the point is inside/at the same position as a given member of the gridPoints array? apologies if this isn’t a good explanation or my code quality is bad, i’m still learning and wouldn’t mind criticism

Welcome!! What an awesome post… formatted code plus some screenshots!

If you keep doing this you’ll soon become an expert!! I highly recommend this approach.

Just a couple of notes about your code to start out.

First, you have some unusual names. gridScaleX and gridScaleY should probably be renamed to gridSizeX or gridDimensionX. Scale isn’t usually used this way.

Second you have Awake() passing in these class variables… if they’re class variables, why not have MakeGrid just pick them up and use them from the class? Unless you contemplate feeding other values into this class’ instance, it’s just extra noise in the function call.

Third you are iterating as long as “less than or equal to.” That’s why you get 5 x 3 when your code says 4 x 2. Keep things like that in sync by always iterating from 0 to N - 1:

for (int i = 0; i < N; i++)     // iterates from 0 to N-1

This is important because an array of N elements will throw an index error if you access element N. The largest element you can get is N-1

So there’s a lot of parts about the supposedly simple “moving in a grid” concept. Does the piece move instantly? Or does it move smoothly? Can it stop halfway between grid points? etc.

If you want to see a simple example of grid movement, check out my MakeGeo and ProximityButtons packages. They both have different examples of grid instantiation, movement within a grid, etc.

For instance, this is the simple “move in a grid” code in ProximityButtons:

https://github.com/kurtdekker/proximity_buttons/blob/master/proximity_buttons/Assets/DemoMoveGridCell/DemoMoveGridCell.cs

proximity_buttons is presently hosted at these locations:

https://bitbucket.org/kurtdekker/proximity_buttons

https://github.com/kurtdekker/proximity_buttons

https://gitlab.com/kurtdekker/proximity_buttons

https://sourceforge.net/projects/proximity-buttons/

and MakeGeo is presently hosted at these locations:

https://bitbucket.org/kurtdekker/makegeo

NOW… as to your actual problem, I am going to tell you how to FIND it, not what it is, simply because I don’t know offhand, not running your code here myself.

Here is the magic sauce to get you deeper into the matrix of gamedev, indeed any programming:

Time to start debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

If your problem is with OnCollision-type functions, print the name of what is passed in!

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

If you are looking for how to attach an actual debugger to Unity: https://docs.unity3d.com/2021.1/Documentation/Manual/ManagedCodeDebugging.html

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

Your script is creating the points/cubes but it’s not adding them to the array.

After line 28 insert this:

gridPoints[i,j]=point;