Converting this JS code to C#

Hello, I have attempted to convert this JS code into C# and I feel that I’m close but not quite there obviously. The idea is to get my player controller to shoot a prefab when I click the mouse button. I’ve attached the prefab as a projectile. Here’s the JS code followed by my C# conversion. I am brand new to coding by the way (just started learning yesterday).

var projectile : Rigidbody;
var damage = 5;

function Update () {
	if(Input.GetButtonDown("Fire1")){
		Spawnpoint = transform.Find("First Person Controller/Main Camera/Spawnpoint");
		SpawnVector = Vector3(Spawnpoint.position.x, Spawnpoint.position.y, Spawnpoint.position.z);
		var clone : Rigidbody;
		clone = Instantiate(projectile, SpawnVector, Spawnpoint.rotation);

		clone.velocity = Spawnpoint.TransformDirection (SpawnVector.forward*20);
	}
}

and mine:

using UnityEngine;
using System.Collections;

public class Projectile : MonoBehaviour {

	private Transform spawnPoint;
	public Rigidbody projectile;
	public int damage = 5;
	
	void  Update (){
		if(Input.GetMouseButtonDown(0)){
			spawnPoint.transform.Find("Player/MainCamera/Spawnpoint");
			Vector3 SpawnVector = new Vector3(spawnPoint.position.x, spawnPoint.position.y, spawnPoint.position.z);
			Rigidbody clone;
			clone = Instantiate(projectile, SpawnVector, spawnPoint.rotation) as Rigidbody;
			clone.velocity = spawnPoint.TransformDirection (Vector3.forward * 20);
		}
	}
}

Thanks for the help, really pushing myself hard to learn scripting.

There are a few differences in the two scripts posted:

  • Input.GetButtonDown("Fire1") vs Input.GetMouseButtonDown(0)
  • Spawnpoint = transform.Find vs spawnPoint.transform.Find
  • "First Person Controller/Main Camera/Spawnpoint" vs "Player/MainCamera/Spawnpoint"

The first and last difference might be deliberate, but the middle one looks certainly wrong. In the JavaScript, it’s creating a variable that stores the spawnpoint that it finds, to then use on the next line. In the C# version, the result ot the Find method is discarded; so I suspect you want to change:

spawnPoint.transform.Find("Player/MainCamera/Spawnpoint");

to

spawnPoint = transform.Find("Player/MainCamera/Spawnpoint");

This will call the Find method on the local objects transform, and assign it to the spawnPoint variable, which is then used in the next line. However, spawnPoint is likely null and will result in a NullReferenceException (which would cause the rest of the Update method to be skipped).