I wanted to make simple lives system,from “TornadoTwins” tutorial,with a new Unity UI system,anyway i got error : Expression ‘UI.Image’ cannot be assigned to.
Am i doing something wrong?
Tutorial :
MyScript :
#pragma strict
import UnityEngine.UI;
var health1 : UI.Image;
var health2 : UI.Image;
var health3 : UI.Image;
static var LIVES : int = 3;
function Start () {
Debug.Log(Lives.LIVES);
}
function Update () {
switch(LIVES)
{
case 3:
UI.Image = health3;
break;
case 2:
UI.Image = health2;
break;
case 1:
UI.Image = health1;
break;
case 0:
// GameOver script here
break;
}
}
You are assigning your Image component to the class Image. Also, once you imported UnityEngine.UI, I think you don’t have to write UI.Image, Image should be enough. (Although I don’t use UnityScript so I could be wrong)
I’m assuming your health images are connected via inspector and exist within your gameObject. You could do the following then (I’ll excuse myself ahead if I wrote something bad with UnityScript, since I use C#):
#pragma strict
import UnityEngine.UI;
var healthImages : Image[];
var lifeCount : int = 3;
function Start () {
Debug.Log(lifeCount);
}
function Update ()
{
var i : int = 0;
for (var image:Image in healthImages)
{
var result : bool = i < lifeCount;
i++;
image.gameObject.SetActive(result);
}
//NOTE: we put this below foreach enumeration so when we hit 0 lifeCount we update last image to enable = false
if (lifeCount <= 0)
{
// call your game over script here
}
}
Have an array of images rather than using hard coded health1, health2, etc… That will allow you to dynamically add as much lives you want without having to revisit the script and add more code if you want to add more lives.
Furthermore, even this script I wrote is a bad example, since you could have only one Image variable and just change it’s Texture2D for whatever image you are using for each life.
I’d like to mention that online tutorials are an okay place to start, but in most cases they don’t teach well in the long run just for the sake of simplicity. Switch cases have their uses, but when dealing with objects it’s better to avoid them since you always have to assume you could have 100, nay, 1000 lives. If you’re planning to have more than 1 object of the same kind within same script, like your health1, health2, etc. I urge you to always use arrays, to make your code scalable to any amount of objects. Always assume you will have 10000+ objects in the future.
Very nice explanation and an excellent code example,works very well,i would never have thought that arrays would be so useful in this case. Thanks man for your time and your help.
Good luck to you!