I try to make my frist game in Unity (checkers) but i ran into a problem i dont unterstand
var spawnedStone = Instantiate(_stonePrefab, new Vector3(x, y, -1), Quaternion.identity);
spawnedStone.name = $"Stone {stone}";
if (y <= 2) _iswhite = true;
else _iswhite = false;
spawnedStone.Init(_iswhite);
stone++;
public class Stone : MonoBehaviour
{
[SerializeField] private Color _black, _white;
[SerializeField] private SpriteRenderer _spriteRenderer;
public void Init(bool _iswhite)
{
_spriteRenderer.color = _iswhite ? _white : _black;
}
}
I am trying to call my Init method of my checkers stone but it does not work somehow but it worked with my tiles for the board
var spawnedTile = Instantiate(_tilePrefab, new Vector3(x, y, 0), Quaternion.identity);
spawnedTile.name = $"Tile {x} {y}";
var _isOffset = (x+y) % 2 == 1;
spawnedTile.Init(_isOffset);
public class Tile : MonoBehaviour
{
[SerializeField] private Color _baseColor, _offsetColor;
[SerializeField] private SpriteRenderer _renderer;
[SerializeField] private GameObject _highlight;
public void Init(bool isOffset)
{
_renderer.color = isOffset ? _offsetColor : _baseColor;
}
anyone knows why ?
this is the error
Thx in advance
Hi @tosendeelemente,
Could you post the exception as text please so I can run translate and see what the exception is.
From the looks of things there are a couple things that could be happening;
- Your _stonePrefab is a GameObject, therefore you’re not able to call functions of the
Stone class.
- Using the
var keyword has confused the compiler believing that the Stone script is a GameObject → its good practice to infer the type explicitly.
Try this:
var spawnedStone = Instantiate(_stonePrefab, new Vector3(x, y, -1), Quaternion.identity);
spawnedStone.name = $"Stone {stone}";
if (y <= 2) _iswhite = true;
else _iswhite = false;
spawnedStone.GetComponent<Stone>().Init(_iswhite);
stone++;
If that works, it’s because you’re not Instantiating your _stonePrefab as a Stone Object but you’re trying to access the method as if it is.
In order to Instantiate as a Stone Object, you need to do the following:
- Create a
GameObject and add the Stone script as a component.
- Change your
_stonePrefab to be of Type Stone
public Stone _stonePrefab
- Code should be as follows
Stone spawnedStone = Instantiate(_stonePrefab, new Vector3(x, y, -1), Quaternion.identity);
spawnedStone.name = $"Stone {stone}";
if (y <= 2) _iswhite = true;
else _iswhite = false;
spawnedStone.Init(_iswhite);
stone++;
Hope that helps!