I’m making a mobile game that uses on-screen UI buttons with Event Triggers to allow the player to control the game character. I have a character selection menu, where the player can pick from a range of characters then I load that character from the menu scene into a game level scene. I achieve this by Instantiating a clone of the character prefab into the scene. The Instantiating of the character works fine, but I’m having issues making the UI buttons link to the Instantiated character.
The Instantiated character has a PlayerController script attached which contains the movement code. The character spawning code is in its own script attached the the GameController GO.
Anyone have any idea what I’m missing? Is it possible the control Instantiated GO with UI buttons? I’m not sure how to link the script in the inspector as the character that is Instantiated in the scene could be any from the list of available characters. It’s quite possible I’m totally missing something. Thanks.
public void ButtonSingleJump(float horizontal)
{
if (GameObject.FindWithTag("Player").GetComponent<Rigidbody2D>().velocity.y == 0)
{
GameObject.FindWithTag("Player").GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpForce));
anim.SetTrigger("SingleJump");
}
}
public void ButtonSlide()
{
if (rb.velocity.y == 0)
{
anim.SetTrigger("Slide");
}
}
public void ButtonDoubleJump()
{
if (rb.velocity.y == 0)
{
rb.AddForce(new Vector2(0, doubleJumpForce));
}
}
Character Spawning script
public class CharacterSpawn : MonoBehaviour
{
public int savedPlayer;
public GameObject shark;
public GameObject player2;
public GameObject player3;
public GameObject player4;
public GameObject player5;
void Awake()
{
savedPlayer = PlayerPrefs.GetInt("SelectedCharacter");
if (savedPlayer == 0)
{
Instantiate (shark, transform.position, transform.rotation);
}
else if (savedPlayer == 1)
{
Instantiate(shark, transform.position, transform.rotation);
}
else if (savedPlayer == 2)
{
Instantiate(player2, transform.position, transform.rotation);
}
else if (savedPlayer == 3)
{
Instantiate(player3, transform.position, transform.rotation);
}
else if (savedPlayer == 4)
{
Instantiate(player4, transform.position, transform.rotation);
}
else if (savedPlayer == 5)
{
Instantiate(player5, transform.position, transform.rotation);
}
}
}