transform.Translate not working in if-statement?

Hey lovely experts,

I’m currently working on a basic 2D game. I want that when the User clicks a Button, a knife should shoot upwards.

However, my Code doesn’t work. I tried a lot, but I don’t see any mistake in the code. So it has to be something with the logic. Here’s the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Spawnhandling : MonoBehaviour {

	public GameObject knife;
	public GameObject knifePosition;
	public float speed;
	public bool shoot;

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {

		if(Input.GetKeyDown("s")){  //just for prototyping
  

			spawnKnife();
		}

		if(shoot == true){

			knife.transform.Translate(0, speed, 0);
		}
		
	}

	public void startShooting(){ // Function which will be called by Button 

		shoot = true;
	}

	public void spawnKnife(){

		Instantiate(knife, knifePosition.transform.position, knifePosition.transform.rotation ); 
	}
}

knife is the prefab you’re instantiating. In your Update method you are modifying the transform of the prefab instead of the spawned instance. Add a GameObject field to store reference to your instance:


GameObject knifeInstance;
public void spawnKnife() {
    knifeInstance = Instantiate(knife, knifePosition.transform.position, knifePosition.transform.rotation);
}

Then use that field to change the position:

void Update() {
...
    if (shoot == true) {
        knifeInstance.transform.Translate(0.0f, speed, 0.0f);
    }
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

 public class Spawnhandling : MonoBehaviour {
 
     public GameObject knife;
     public GameObject knifePosition;
     public float speed;
     public bool shoot;
 
     // Use this for initialization
     void Start () {
         
     }
     
     // Update is called once per frame
     void Update () {
 
         if(Input.GetKeyDown("s")){  //just for prototyping
   
 
             spawnKnife();
         }
 
         if(shoot == true){
 
             knife.transform.position += new Vector3(0.0F, speed, 0.0F);
         }
         
     }
 
     public void startShooting(){ // Function which will be called by Button 
 
         shoot = true;
         print("shoot");
     }
 
     public void spawnKnife(){
 
         Instantiate(knife, knifePosition.transform.position, knifePosition.transform.rotation );
         print("spawn");
     }
 }

Try with this code. I added some print() methods to see if you actually call all the methods correctly and I also changed transform.Translate with transform.position +=…