- Home /
How can I add knockback to a prefab?
I am making a 2d platformer game for a hs project, I currently have a player game object that experiences knockback with enemies perfectly, but when he dies, the prefab for some reason doesn't experience knockback, even when it is the exact copy of the original game object. I have a hunch that it is something to do with this line var player = GetComponent();. This is the current script for my knockback. The variable is my player controller script
private void OnCollisionEnter2D(Collision2D other)
{
if (currentHealth > 0)
{
var player = GetComponent<PlayerMovement>();
if (other.gameObject.tag == "Enemy")
{
TakeDamage(20);
player.knockbackCount = player.knockbackLength;
if (player.facingRight)
{
player.knockFromRight = true;
}
else if(!player.facingRight)
{
player.knockFromRight = false;
}
}
and this is my code for respawning the prefab
public void Respawn() {
GameObject Player = Instantiate(playerPrefab, spawnPosition.position, Quaternion.identity);
cam.Follow = Player.transform;
And then this is the script inside my player controller
if (canMove && knockbackCount <= 0)
{
rb.velocity = new Vector2(movementSpeed * mx, rb.velocity.y);
}
else
{
if (knockFromRight)
{
rb.velocity = new Vector2(-knockback, 0.0f);
}
if(!knockFromRight)
{
rb.velocity = new Vector2(knockback, 0.0f);
}
knockbackCount -= Time.deltaTime;
Any help would be appreciated and let me know if you need more explained.
Answer by GeroNL · Aug 29, 2021 at 07:19 AM
Hello, if you use the prefab and it has reference you need to find in Start or in Awake, like this:
// example in enemy code
// instans
Player player;
private Awake()
{
player = GameObject.Find("NameGameObject that have Player)").GetComponent<Player>();
}
Maybe it not work cause your some or your prefab not reference some object.
Hope it help.
@GeroNL I don't exactly understand what you are trying to say sorry, I am quite new to this whole thing. I already have an awake function that is used to create an instance to help respawn my player that is attached to a different script. Are you suggesting I try the code above in that function or in the one where my player takes knockback? private void Awake() { instance = this; }
Your enemy code has a player? if it has, are you instant or set it on unity inspector? if it like that, the enemy in scene doing well, but not for prefab. prefab can not be set with object out of it(the prefab, but it can set the objects in its child). to set the player you need to find it with code that i already suggest, put it on Start or Awake, and if you already have that(Awake or Start) just put on it on the first line, cause if you use it (like : player.something) you need to set it first.
@GeroNL Thank you so much, it worked. Absolute legend and I hope you have a good day wherever you are!