I am following a tutorial on 2048 in unity. He is using a Text and Image to render his 'tiles' and I decided to use a sprite because I have pre-made tiles in adobe. The first bit of code is the TileStyleHolder and the second script is called Tile(to be attached to the actual sprite/image itself that will be enabled/disabled.)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class TileStyle
{
public Sprite tile_number;
}
public class TileStyleHolder : MonoBehaviour
{
//SINGLETON
public static TileStyleHolder Instance;
public TileStyle[] TileStyles;
void Awake()
{
Instance = this;
}
}
AND THIS IS THE SECOND SCRIPT~~
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Tile : MonoBehaviour
{
public int Number
{
get
{
return number;
}
set
{
number = value;
if (number == 0)
SetEmpty();
else
{
ApplyStyle(number);
SetVisible();
}
}
}
private int number;
private Sprite TileSprite;
void Awake()
{
TileSprite = transform.Find("numcell").GetComponent<Sprite>();
}
void ApplyStyleFromHolder(int index)
{
TileSprite = TileStyleHolder.Instance.TileStyles[index].tile_number.ToSprite();
}
void ApplyStyle(int num)
{
switch (num)
{
case 2:
ApplyStyleFromHolder(0);
break;
case 4:
ApplyStyleFromHolder(1);
break;
case 8:
ApplyStyleFromHolder(2);
break;
case 16:
ApplyStyleFromHolder(3);
break;
case 32:
ApplyStyleFromHolder(4);
break;
case 64:
ApplyStyleFromHolder(5);
break;
case 128:
ApplyStyleFromHolder(6);
break;
case 256:
ApplyStyleFromHolder(7);
break;
case 512:
ApplyStyleFromHolder(8);
break;
case 1024:
ApplyStyleFromHolder(9);
break;
case 2048:
ApplyStyleFromHolder(10);
break;
case 4096:
ApplyStyleFromHolder(11);
break;
default:
Debug.LogError("Check the numders that you pass to ApplyStyle");
break;
}
}
private void SetVisible()
{
TileSprite.enabled = true;
}
private void SetEmpty()
{
TileSprite.enabled = false;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
{ }
button! – derHugoSprite
is not a component so you can't useGetComponent<Sprite>
As said you have to find the component using that sprite like e.g.SpriteRenderer
orImage
and enable/disable that instead – derHugoSprite
come from? Where is it used? What is the expected behavior you are trying to achieve? – derHugo