Dear gods of Unity, how do I set the 3d position of a sprite on a world-space canvas with a c# script?
The canvas is for a cockpit display and the sprite and it’s position changes depending on the mode. There are too many modes for me to have a different canvas for each sprite and I can’t just set the position via the editor.
Ideally, I would like to have multiple sprites with different positions on 1 worldspace canvas. Please can you suggest a way of doing this?
The Idea is to use arrays in order to change modes.
FIRST CREATE AN EMPTY GAMEOBJECT AND ASSIGN THIS CODE TO THE GAMEOBJECT.
STEP: 1 - Create the amount of sprites you need and group them in empty gameobjects.
STEP: 2 - Set the size of the array depending on the number of your modes.
STEP: 3 - Enter the gameobjects in the array.
STEP: 4 - Set the noOfModes int. Depending on your number of modes.
public GameObject[] modes;//Holds all the modes.
public int noOfModes = 4;//Enter the number of modes you need to have in your game.
private int modeNumber = 0;//The current mode to active.
// Use this for initialization
void Start ()
{
modes[1].SetActive(false);//In case we have 4 modes we disable the last three modes leaving the first one active. Or modes[0].
modes[2].SetActive(false);
modes[3].SetActive(false);
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown("space"))//Executes the command when the user pressed SPACEBAR.
{
ModeSwitch();
}
}
void ModeSwitch ()
{
modes[modeNumber].SetActive(false);//Disables the current mode.
modeNumber += 1;
if(modeNumber > noOfModes)//If modeNumber exceeds the no. of modes the modeNumber comes back to 0.
{
modeNumber = 0;
}
modes[modeNumber].SetActive(true);//Enables the new mode.
}
If it does not work for you let me know. Hope it helps.