I am trying to create the Snake game in Unity, based on this video tutorial. I have also viewed this tutorial.
I have created the new project with the 3D template and manually added the Canvas. I created a prefab from an Image which loads a texture from the Assets. I have this code:
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public GameObject whiteCellPrefab;
int N = 30, M = 20, size = 16;
// Start is called before the first frame update
void Start()
{
Transform p = GameObject.Find("Canvas").transform;
for (int i = 1; i <= N; ++i)
{
for (int j = 1; j <= M; ++j)
{
GameObject g = Instantiate(whiteCellPrefab, p);
g.transform.localPosition = new Vector3(i * size, j * size);
}
}
}
// Update is called once per frame
void Update()
{
}
}
If I manually add a prefab instance to the Canvas, it is positioned as I want: in the bottom-left corner. But the script above, attached to the Main Camera object, creates the Image objects starting from the center point of the Canvas towards the top-right corner of the Canvas.
In the example shown here, I also added a new prefab instance to the Canvas in the Unity editor. It is positioned correctly even when play testing but the ones added with the script are shown somewhere else.
Screenshots
Download my example
I tried to explain all the steps involved in my problem above, but here is the repo with my problem.
Thank you.