- Home /
OnMouseDown instantiates object in different spot
So I'm making tic-tac-toe game for practice and I created a square prefab that has a collider on it that I put in each block of the game board. I created a "Buttons" script that is attached to the squares that uses OnMouseDown.
PlayerText playerText;
SpawnSymbols spawnSymbols;
private void Start()
{
spawnSymbols = FindObjectOfType<SpawnSymbols>();
playerText = FindObjectOfType<PlayerText>();
}
private void OnMouseDown()
{
spawnSymbols.SpawnPlayerSymbol();
GetComponent<Collider2D>().enabled = false;
playerText.UpdatePlayerText();
}
I initially did all of my instantiating within this script and it worked perfectly. The X's and O's were spawning where they were supposed to. But I then decided to put the instantiating on a separate script for better readability. This script looks like:
[SerializeField] GameObject playerX;
[SerializeField] GameObject playerCircle;
Players player;
private void Start()
{
player = FindObjectOfType<Players>();
}
public void SpawnPlayerSymbol()
{
if (player.playersTurn)
{
Instantiate(playerX, transform.position, transform.rotation);
player.playersTurn = false; ;
}
else
{
Instantiate(playerCircle, transform.position, transform.rotation);
player.playersTurn = true;
}
}
I also attached this script to the Square prefab so the transform should be exactly the same as it was on the previous script because they are both attached to the same objects, but for some reason when I click it instantiates the the symbols in one block no matter which block I click on. I have no idea what's going on, but I have a feeling it has something to do with the way OnMouseDown works. I'm sure it's something blatantly obvious, but I just can't see it. Any help would be greatly appreciated!
Answer by BmoreG · Jul 13, 2020 at 08:27 PM
So I seemed to have figured it out. It would appear using spawnSymbols = FindObjectOfType<SpawnSymbols>();
was the cause behind the issue. I changed it to spawnSymbols = GetComponent<SpawnSymbols>();
. I'm not entirely sure why this fixed the issue. I think it may be because of the fact that I have multiple "Square" game objects in my scene that have the instantiating script on them and FindObjectOfType (from what I understand) only works if you have one instance of the script that you are using. Please anyone feel free to correct me or chime in if there is something I'm missing here.
EDIT: I ended up using this as my final code: GetComponent<SpawnSymbols>().SpawnPlayerSymbol();
This seems like the most practical since both scripts are attached to the same gameobject.