- Home /
Changing 2D Player Sprite on Trigger using C#
Hi dear community,
i am still new to C# in unity. I am grateful for a solution to this little problem i have.
My objective is to change the Player's Sprite once they have collected a game item.
Please see my script below which does nothing to the player when she collides into her helmet.
What am I missing?
Thank you so much, Simone
using System.Collections; using System.Collections.Generic; using UnityEngine;
/// /// Makes the Player Walk Left & Right, Jump using animations /// public class GigiPlayerCtrl : MonoBehaviour { Rigidbody2D rb; public int speedBoost; public float jumpSpeed; // set this to 600 SpriteRenderer sr; Animator anim; bool isJumping; public Sprite gigiHelmet;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
sr = GetComponent<SpriteRenderer>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
float playerSpeed = Input.GetAxisRaw("Horizontal"); // value will be negative 1, -1 or 0.
playerSpeed *= speedBoost; // playerSpeed = playerSpeed * speedBoost
if (playerSpeed != 0)
MoveHorizontal(playerSpeed);
else
StopMoving();
if (Input.GetButtonDown("Jump"))
Jump();
}
void MoveHorizontal(float playerSpeed)
{
rb.velocity = new Vector2(playerSpeed, rb.velocity.y);
if (playerSpeed < 0)
sr.flipX = true;
else if (playerSpeed > 0)
sr.flipX = false;
if (!isJumping)
anim.SetInteger("State", 1);
}
// Update is called once per frame
void StopMoving()
{
rb.velocity = new Vector2(0, rb.velocity.y);
if (!isJumping)
anim.SetInteger("State", 0);
}
void Jump()
{
isJumping = true;
rb.AddForce(new Vector2(0, jumpSpeed)); // Make the player jump upwards ( the Y axis)
anim.SetInteger("State", 2);
AudioManager.instance.PlaySFX(1);
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Ground"))
{
isJumping = false;
}
else if (other.gameObject.CompareTag("Helmet"))
{
gameObject.GetComponent<SpriteRenderer>().sprite = gigiHelmet;
}
}
}
Answer by VisionElf · Sep 20, 2021 at 01:59 PM
Have you checked that your OnCollisionEnter2D is correctly called?
Did attached the tag "Helmet" to your gameObject you're trying to collide with?
Have you assigned the gigiHelmet to a non-null value?
@VisionElf Have you checked that your OnCollisionEnter2D is correctly called? I am not to sure how to check that..
Did attached the tag "Helmet" to your gameObject you're trying to collide with? Yep!
Have you assigned the gigiHelmet to a non-null value? I do not know how to do that.
Will the animations be impacted, i tried to do this via animator but could not get it to work .
Thank you for your time.
You can use Debug.Log in your OnCollisionEnter2D method. If you see the message in the console, it means it's correctly called.
Answer by Littlestrings · Sep 21, 2021 at 09:27 PM
@VisionElf thank you, i will try that.
How do I assign the gigiHelmet to a non-null value? What does that do?
Your answer