- Home /
Question about GetComponent
I'm running into a error with the GetComponent portion of my script. Can anybody tell me what I missed? I have the script its looking for attached to the gameobject. But I'm still getting this error in the console
" Type UnityEngine.Object' does not contain a definition for
GetComponent' and no extension method GetComponent' of type
UnityEngine.Object' could be found (are you missing a using directive or an assembly reference?)"
using UnityEngine;
using System.Collections;
public class AirTurret : MonoBehaviour {
public GameObject myProjectile;
public float reloadTime = 1f;
public float turnSpeed = 5f;
public float firePauseTime =.25f;
public float errorAmount = .001f;
public Transform myTarget;
public Transform[] muzzlePositions;
public Transform pivot_Tilt;
public Transform pivot_Pan;
public Transform aim_Pan;
public Transform aim_Tilt;
private float nextFireTime;
// Use this for initialization
void Start () {
}
void Update () {
if(myTarget)
{
aim_Pan.LookAt(myTarget);
aim_Pan.eulerAngles = new Vector3(0, aim_Pan.eulerAngles.y, 0);
aim_Tilt.LookAt(myTarget);
pivot_Pan.rotation = Quaternion.Lerp(pivot_Pan.rotation, aim_Pan.rotation, Time.deltaTime * turnSpeed);
pivot_Tilt.rotation = Quaternion.Lerp(pivot_Tilt.rotation, aim_Tilt.rotation, Time.deltaTime * turnSpeed);
if(Time.time >= nextFireTime)
{
FireProjectile();
}
}
}
void OnTriggerEnter(Collider other )
{
if(other.gameObject.CompareTag("Enemy"))
{
nextFireTime = Time.time +(reloadTime*.5f);
myTarget = other.gameObject.transform;
}
}
void OnTriggerExit(Collider other)
{
if(other.gameObject.transform == myTarget)
{
myTarget = null;
}
}
void FireProjectile()
{
// audio.Play();
nextFireTime = Time.time+reloadTime;
int m = Random.Range(0,6);
var newMissile = Instantiate(myProjectile, muzzlePositions[m].position, muzzlePositions[m].rotation);
newMissile.GetComponent<Projectile_Missle>().myTarget = myTarget;
}
}
Answer by robertbu · Sep 27, 2013 at 01:23 AM
Replace line 64 with this:
GameObject newMissile = Instantiate(myProjectile, muzzlePositions[m].position, muzzlePositions[m].rotation) as GameObject;
By using 'var' and by not casting the Instantiate() somehow, the compiler sets newMissile to a base type (and not a game object).
The problem isn't the use of "var", it's that it was missing the "as GameObject" cast. The cast will cause the type to be correct if you use var.
Thanks for your help guys. I had to look up what exactly you meant by cast and I got it from there. Thanks for the information.