- Home /
Problem with referencing gameobjects in a if statement
I'm following a tutorial that's in javascript and I'm converting the code over to C# and I'm running into a problem at the end of the tutorial. The problem I'm having is running into this line of code:
for(theMuzzlePos in muzzlePositions) { Instantiate(myProjectile, theMuzzlePos.position, theMuzzlePos.rotation); Instantiate(muzzleEffect, theMuzzlePos.position, theMuzzlePos.rotation); }
C# apparently does not recognize "in" in the conditional statement. What can I do to change this and reference those gameobjects?
using UnityEngine;
using System.Collections;
public class Turret_Script : MonoBehaviour {
public GameObject myProjectile;
public float reloadTime = 1f;
public float turnSpeed = 5f;
public float firePauseTime =.25f;
public GameObject muzzleEffect;
public float errorAmount = .001f;
public Transform myTarget;
public Transform[] muzzlePositions;
public Transform turretBall;
private float nextFireTime;
private float nextMoveTime;
private Quaternion desiredRotation;
private float aimError;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(myTarget)
{
if(Time.time >= nextMoveTime)
{
CalculateAimPosition(myTarget.position);
turretBall.rotation = Quaternion.Lerp(turretBall.rotation, desiredRotation, Time.deltaTime*turnSpeed);
}
if(Time.time >= nextFireTime)
{
FireProjectile();
}
}
}
void OnTriggerEnter(Collider other )
{
if(other.gameObject.tag == "Enemy")
{
nextFireTime = Time.time +(reloadTime*.5);
myTarget = other.gameObject.transform;
}
}
void OnTriggerExit(Collider other)
{
if(other.gameObject.transform == myTarget)
{
myTarget = null;
}
}
void CalculateAimPosition(Vector3 targetPos)
{
var aimPoint = new Vector3(targetPos.x+aimError, targetPos.y+aimError, targetPos.z+aimError);
desiredRotation = Quaternion.LookRotation(aimPoint);
}
void CalculateAimError()
{
aimError = Random.Range (-errorAmount, errorAmount);
}
void FireProjectile()
{
audio.Play();
nextFireTime = Time.time+reloadTime;
nextMoveTime = Time.time+firePauseTime;
CalculateAimError();
for(theMuzzlePos in muzzlePositions)
{
Instantiate(myProjectile, theMuzzlePos.position, theMuzzlePos.rotation);
Instantiate(muzzleEffect, theMuzzlePos.position, theMuzzlePos.rotation);
}
}
}
Answer by syclamoth · Sep 23, 2013 at 02:16 AM
The issue here is a slight difference in the syntax for collection iterators in C#. You should instead be using
foreach(Transform theMuzzlePos in muzzlePositions) {
// blah blah blah
}
thank you that was exactly it. I've never ran into in before in if statements so I was completely clueless.
Also, this is a for-loop. If-statements work pretty much the same way in C# as they do in Unityscript.