- Home /
Pass parameters to an instance
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"?
Answer by fafase · Oct 27, 2013 at 10:39 PM
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;
}
}
Never tought I'll recieve an answer so fast, thank you. I have a temporary solution right now, in which I can shoot lots of arrows with no problem. I use Quaternion.Euler to set an angle for instantiated arrow and control its flight with fixed force.
The problem stays, i want to shoot it that way but i want the force to be calculated depending on how long the shooting button been held by the player. So i need a way to pass it to the "arrow_script".
This is a total different issue, you are not looking for an angle but just for a period.
Your answer
![](https://koobas.hobune.stream/wayback/20220613120744im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
My shooting system wont work, help 1 Answer
Shooting Cannons from a boat 1 Answer
Issue with Timed Shooting in C# 1 Answer
Control amount of bullets 2 Answers
Field of view not working correctly, firing from behind 0 Answers