I want to make my character shoot an arrow. I have “shooting_script” script assigned to my character, that will instantiate an arrow from arrowprefab. An arrow has “arrow_script” assigned, that will control its rotation and trajectory during flight. The question is, what is the best way to pass angle and force parameters to “arrow_script” after instantiating arrow from “shooting_script”?
Using GetComponent seems the way.
Considering you control only one arrow at a time:
arrow_script _arrowScript;
public GameObject arrow;
public float maxTime; // This to avoid light speed if pressing too long
void CreateArrow(float time)
{
GameObject obj = (GameObject)Instantiate(arrow);
_arrowScript = obj.GetComponent<arrow_script>();
_arrowScript.time = Mathf.Clamp(time,0,maxTime);
}
Now anywhere else in your script you can play with the arrow_script using the reference.
When a new arrow is created the previous one is overwritten and now you can control the new one.
EDIT: I modified a little the answer above but it is what it is the period of time the user is pressing you are after.
float _timer = 0;
void Update(){
if(Input.GetButton(KeyCode.Space))_timer +=Time.deltaTime;
if(Input.GetMButtonUp(KeyCode.Space))
{
CreateArrow(_timer);
_timer = 0;
}
}