- Home /
Why I cant attach a script from a prefab to another prefab?,Why i cannot attach a script from a prefab in another prefab?
Hi, Im doing a rocket and I have referenced another script to take the position of the fire point to calculate the speed, but in the inspector I cant attach the script to the prefab. How can I solve this??
public class Rocket : MonoBehaviour {
float currentSpeed;
public float speed = 0.25f;
public AnimationCurve curvi;
public Weapon weapon;
public Rigidbody2D rb;
private void Start()
{
weapon.GetComponent<Weapon>();
}
void FixedUpdate () {
rb.velocity = transform.right * speed;
}
void Update () {
currentSpeed = Vector2.Distance(weapon.firePoint.position, transform.position);
speed = curvi.Evaluate(currentSpeed);
}
What does Unity give you as an error when you try to attach the script to a prefab in the scene?
Answer by tormentoarmagedoom · Jun 07, 2019 at 08:18 AM
Hello.
You are missunderstanding somethig...
You declare a Weapon variable (i supose its the script you talking about) as public. So I understand yopu pretend to attach via inspector this variable.
Then in Start, you do this:
weapon.GetComponent<Weapon>();
What's this? whats the objective of this line? What you think is doing? i does nothing, you dont give any "order", dont assigne any value to any variable, its not a "command". ITs like you say:
"Get the component of this object" ... And I ask and what? if you acces it is to do something, change a value, assign it to a variable, destroy it, something... but you dont do anythig there...
You can do this: Replace declaration of "Weapon" varaible to be a GameObject type variable, so you can assign the gameobject to the variable via inspoector. Then acces its component to assign it to your private "weapon" variable
public class Rocket : MonoBehaviour {
float currentSpeed;
public float speed = 0.25f;
public AnimationCurve curvi;
public GameObject weaponObject;
private Weapon weapon;
public Rigidbody2D rb;
private void Start()
{
weapon = weaponObject.GetComponent<Weapon>();
}
void FixedUpdate () {
rb.velocity = transform.right * speed;
}
void Update ()
{
currentSpeed = Vector2.Distance(weapon.firePoint.position, transform.position);
speed = curvi.Evaluate(currentSpeed);
}
See the diference??
You can directly assign the Weapon variable without need of declaring first the object, but i done this to show you the "logic" of all steps. As i see you have some missunderstandings about declarations and relation betwen objects and compoentns, you should spend some time watching more tutotrials about this.
Bye! :D
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Using a variable value with GetComponent 1 Answer
How Do I Access and Change Items in a List on Another Script? 2 Answers