- Home /
I'm having problems with referencing other scripts.
I'm having a bit of trouble referencing a script in my game.
What I have is a projectile that should shoot out of the gun, but thescript that contains the bool I'm using to declare whether or not the gun is shooting is in the gun itself. So I decided to try and reference it from the launcher script
It can't get it to work, though, here's the code as it is right now:
using UnityEngine;
using System.Collections;
public class Launcher : MonoBehaviour {
public Rigidbody projectile; //Variable to hold our projectile object of type Rigidbody.
public short speed = 999; //Variable 'speed' which determines how fast the projectile will shoot.
public RayShoot gun1Script = transform.parent.gameObject.GetComponent<RayShoot>();
void Start ()
{
collisionParticle.emit = false;
}
void Update ()
{
if (gun1Script.shooting) //If player clicks left mouse button.
{
Rigidbody instantiatedProjectile = (Rigidbody)Instantiate(projectile, transform.position, transform.rotation);
instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0, 0, speed));
Destroy(instantiatedProjectile.gameObject, 10);
//print("IT WORKS!!!");
//Physics.IgnoreCollision(instantiatedProjectile.collider, transform.collider);
}
}
}
I'm getting this error message:
Assets/Tutorial Stuff/Scripts/C#/Launcher.cs(8,38): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `UnityEngine.Component.transform'
What do I do?
I noticed I made a mistake, the object that had the script, wasn't the parent, but IT'S parent, so I set it it public, and in Unity itself, I just dragged the object with the script into the slot in the Inspector, and it did the trick! Something tells me this isn't the right way of doing it, but it works just fine!
Answer by Eric5h5 · Jan 05, 2013 at 06:24 PM
You should only declare variables outside functions. Actual code that initializes variables should always go inside functions, in this case Awake or Start.
private RayShoot gun1Script;
void Awake () {
gun1Script = transform.parent.GetComponent<RayShoot>();
}
By the way, you don't need TransformDirection here, you can just do
instantiatedProjectile.velocity = transform.forward * speed;
Answer by RazorCut · Jan 05, 2013 at 06:49 PM
You cannot initialize gun1Script member during object construction. You have to do it in Awake(), Start(), or later. In your case, Awake() will fix it for you.
Your answer
Follow this Question
Related Questions
How do you reference a GameObject in a C# script that is a part of that GameObject? 1 Answer
C# utilities functions in other script 1 Answer
How do I check if an Object isn't moving? (C#) 1 Answer
Change value of integer based on string input in a separate script 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers