I’m pretty new to Unity and was trying to convert the scripts from the FPS tutorial from javascript to c#. I can’t seem to get it right however, could anyone of you please look at it to see what’s wrong with it?
Thanks in advance.
The PlayerWeapon C# script:
using UnityEngine;
using System.Collections;
public class PlayerWeapon : MonoBehaviour {
void Awake()
{
SelectWeapon(0);
}
void Update()
{
if (Input.GetButton ("Fire1"))
{
BroadcastMessage("Fire");
}
if (Input.GetKeyDown("1"))
{
SelectWeapon(0);
}
else if (Input.GetKeyDown("2"))
{
SelectWeapon(1);
}
}
public void SelectWeapon(int index)
{
for (int i=0;i<transform.childCount;i++)
{
if (i == index)
transform.GetChild(i).gameObject.SetActiveRecursively(true);
else
transform.GetChild(i).gameObject.SetActiveRecursively(false);
}
}
}
PlayerWeapon Java script:
function Awake() {
// Select the first weapon
SelectWeapon(0);
}
function Update () {
// Did the user press fire?
if (Input.GetButton ("Fire1"))
BroadcastMessage("Fire");
if (Input.GetKeyDown("1")) {
SelectWeapon(0);
}
else if (Input.GetKeyDown("2")) {
SelectWeapon(1);
}
}
function SelectWeapon (index : int) {
for (var i=0;i<transform.childCount;i++) {
// Activate the selected weapon
if (i == index)
transform.GetChild(i).gameObject.SetActiveRecursively(true);
// Deactivate all other weapons
else
transform.GetChild(i).gameObject.SetActiveRecursively(false);
}
}
Explosion script: I don’t know what to fill in at “foreach (… hit in colliders) {”. it used to say “foreach (var hit in colliders) {” in the javascript file.
using UnityEngine;
using System.Collections;
public class MachineGun : MonoBehaviour {
public int range = 100;
public float fireRate = 0.05f;
public float force = 10.0f;
public float damage = 5.0f;
public int bulletsPerClip = 40;
public int clips = 20;
public float reloadTime = 0.5f;
ParticleEmitter hitParticles;
public Renderer muzzleFlash;
int bulletsLeft = 0;
float nextFireTime = 0.0f;
float m_LastFrameShot = -1f;
// Use this for initialization
void Start () {
hitParticles = GetComponentInChildren<ParticleEmitter>();
if (hitParticles)
{
hitParticles.emit = false;
}
bulletsLeft = bulletsPerClip;
}
void LateUpdate()
{
if (muzzleFlash)
{
if (m_LastFrameShot == Time.frameCount)
{
muzzleFlash.transform.localRotation =
Quaternion.AngleAxis(Random.Range(0, 359), Vector3.forward);
muzzleFlash.enabled = true;
if (audio)
{
if (!audio.isPlaying)
audio.Play();
audio.loop = true;
}
}
else
{
muzzleFlash.enabled = false;
enabled = false;
if (audio)
{
audio.loop = false;
}
}
}
}
public void Fire ()
{
if (bulletsLeft == 0)
return;
if (Time.time - fireRate > nextFireTime)
nextFireTime = Time.time - Time.deltaTime;
while( nextFireTime < Time.time bulletsLeft != 0)
{
FireOneShot();
nextFireTime += fireRate;
}
}
public void FireOneShot ()
{
Vector3 direction = transform.TransformDirection(Vector3.forward);
RaycastHit hit;
if (Physics.Raycast (transform.position, direction, hit, range))
{
if (hit.rigidbody)
hit.rigidbody.AddForceAtPosition(force * direction, hit.point);
if (hitParticles)
{
hitParticles.transform.position = hit.point;
hitParticles.transform.rotation =
Quaternion.FromToRotation(Vector3.up, hit.normal);
hitParticles.Emit();
}
hit.collider.SendMessageUpwards("ApplyDamage", damage,
SendMessageOptions.DontRequireReceiver);
}
bulletsLeft--;
m_LastFrameShot = Time.frameCount;
enabled = true;
if (bulletsLeft == 0)
Reload();
}
public IEnumerator Reload () {
yield return new WaitForSeconds(reloadTime);
if (clips > 0)
{
clips--;
bulletsLeft = bulletsPerClip;
}
}
public int GetBulletsLeft ()
{
return bulletsLeft;
}
}
I’ll add the other scripts once this one works so you won’t be overwhelmed with code.
I am not familiar with the FPS tutorial, but I can tell you that that code is correct in the sense that there are no compilation issues. I suspect you are having an issue with how it works in your game. If you need help with this you need to specify exactly what your issue is. Perhaps you have both scripts named the same and they are causing issues. For example you could have PlayerWeapon.js and PlayerWeapon.cs, but the engine sees them without their file extensions. I dont know if that would cause an issue, but when I converted the 2D platformer tutorial to C# I just appended ‘CS’ to the end of each file name to avoid any ambiguity.
I have recently removed the javascript files and closed to project and reopened it. It did change the outcome of the game abit. But since the javascript files are gone that shouldn’t be the source of the problem.
I’ll add the original javascript code as well to make it clearer for those who never saww the FPS tutorial.
Thanks,
Dastrus
Edit: Furthermore I’ve posted the code which gives me an error at the moment. It’s from the Explosion script.
I think that should fix your issue. One thing you need to keep in mind when converting to C# is that JavaScript automatically calls the instantiator for a class when you create a new one meaning that often times in JS code (at least in Unity) people will forgo adding that extra bit of text. You will see issues with Vector3s a lot too since they get used all over the place in games. If you get these errors, find out where the object is being created and try adding “= new ObjectType();” where ObjectType is the type of object that is causing you problems. Hope this helps.
Actually, ShiftyMcCan, that method has an “out” flag on the RaycastHit object. I believe the correct solution is to properly mark it so the method can write the object. In this case, you should not initialize “hit” because it will be initialized/assigned within the Physics.Raycast method. But you need to mark it with the “out” flag to work.
RaycastHit hit;
if (Physics.Raycast (transform.position, direction, out hit, range))
Initializing “hit” to a new instance will get rid of the current error but replace it with another one complaining about the lack of “out”.
He was simply asking how to get rid of that error, which I told him how to right? Hah, you are right though. That is what you need to do, but trust me that you will need to manually set some variables equal to their instantiator at some point, so hopefully both of these answers solved a few future issues for you. I have never seen a method that uses an out flag before I started working with Unity and only then have I seen it one time while converting the 2D Platformer Tutorial.
I already tried = new RaycastHit(); since I already have some experience with XNA. However, I never knew about “out” so thank you for that.
MachineGun.cs works now, except for the fact that reload doesn’t seem to work. Doe anyone of you see some error in it? Maybe because it’s a IEnumerator but I don’t really know. I tried to put Debug.Log(“Reload”); in it but it doesn’t show. I put it before the Reload(); command in the FireOneShot method and it did got that far.
So we gotta help you finish the thing before you are grateful? I see how it is
I also agree your issue is likely in that snippet of code. Add in “Debug.Log(transform.rotation);” above the line “Rigidbody instantiatedProjectile = Instantiate(proj…” and read your console log. If it is always giving you the same value then something else is wrong with the rocket launcher. Something that is positioning the thing likely has a logic error. I think it may also be an issue if only the second and fourth value changes which means it’s only rotating around the y-axis.