- Home /
Trying to change character model on mouse down
Ok so I'm fairly new to unity2D so my apologies for anything that should be obvious.
I have a player sprite with a controller and walking animations. In the scene, there is armor hanging on the wall and the intention is for the player to put on the armor when it is clicked. I have a prefab of the player in the armor with a controller and walking animations (and I already have a script to have the armor on the wall disappear), I just cannot seem to figure out how to have the player's character model switch when clicked. I don't have any scripts to show since I don't even know where to start with this particular action.
Any help would be very much appreciated!!
Answer by AaronBacon · Jun 03 at 06:47 AM
If all you want is to remove the old player and spawn in the new Prefab, You can do a raycast at the mouse position to check for if the mouse click "Collides" with this object (Note the armour has to have a collider on it). You can have a reference to the player and the new armoured version and use GameObject.Destroy(playerReference)
and GameObject.Instantiate(armouredPrefab)
. to swap them out. So on the armour you'd do something like:
void Update()
{
if (Input.GetMouseButtonDown(0)) // If Left Click is Pressed
{
Vector3 mousePos =
Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(new Vector2(mousePos.x, mousePos.y), Vector2.zero);
if(hit.collider != null) // If the Mouse hit something
{
if (hit.collider.gameObject == this.gameObject) // if the something is this object
{
RunSwapArmourFunction(); // Swap the Armour
}
}
}
}
⠀
However I'd say destroying and replacing the player may not be the best way to do it. It's going to largely depend how the player is set up and animated, I assume you're using Bone based animation, where each section of the player is a separate sprite which is then physically moved in animation, as opposed to a spritesheet animation where each animation is made of manually drawn frames.
⠀
If that's the case, what you want to look into is the SpriteRenderer Component on the Player, specifically changing the sprite property to another sprite. Easiest way is to have the new Sprite stored in a variable and just set its sprite to that when it needs to swap.
Your answer
![](https://koobas.hobune.stream/wayback/20220613061321im_/https://answers.unity.com/themes/thub/images/avi.jpg)