|
I'm trying to read a public float called shootForce contained in a monoBehaviour class called player001controls using a monoBehaviour script called missileControls with cSharp. player001controls.cs (extract) } missileControls.cs (extract) This executes, but when I fire a missile I get this error :
Removing the 'new' from gives the error
I want to be able to access the float shootForce at runtime, read from player001controls (or any other script).
(comments are locked)
|
|
OK, heres my solution (final) Declaration : } Invocation : Execution :
(comments are locked)
|
|
To create an instance of a MonoBehaviour class at runtime you have to use AddComponent because all components can't exist on it's own. They always need to be attached to a GameObject. If you want to create a script instance on the same GameObject where this script is attached to just use: Ohh a little sidenote: classnames always should start with a capital letter. It get's very very difficult to read code where you mix typenames with variable names. That are some basic programming conventions.
(comments are locked)
|
|
I think you you make a prefab out of the player001controls and Instantiate it, you'll be good to go. public GameObject player001PreFab; // set this with inspector player001controls missileControl; GameObject gObj = Instantiate(player001PreFab, Vector3.zero, Quaternion.identity); missileControl = (player001controls)gObj.GetComponent(typeof(player001controls));
(comments are locked)
|
|
I recommend that you start by reading this: The above link explains some of the basic concepts of how scripts interact in Unity.
(comments are locked)
|

I don't see how what Unity tells you doesn't solve your problem. A MonoBehaviour is something to be attached to a Game Object.
missileControls.cs is a script component added to my missile prefab player001controls.cs is a script component added to my player GameObject
I think you you make a prefab out of the player001controls and Instantiate it, you'll be good to go.
public GameObject player001PreFab; // set this with inspector
player001controls missileControl = Instantiate(player001PreFab, Vector3.zero, Quaternion.identity);
One of the basic rules of Unity is that you don't use constructors with MonoBehaviours. This means you don't use the "new" operator. You attach scripts to GameObjects and reference them with public variables or GetComponent.
That has got to be one of the most descriptive and helpful compiler messages you're ever going to see (Unity rocks)!