- Home /
Instantiate only One Object
I am trying to be able to place boards down when they collide with other objects and you click. However if it collides with more than one object it places more than one board in the same spot. How can I change it so that it only places one board? This is the script on the plank that you use to decide where to place it.
void OnCollisionStay(Collision collisionInfo){
if (Input.GetMouseButtonDown(0) && placeone == false){
Instantiate(woodPlank, transform.position,transform.rotation);
placeone = true;
}
if (Input.GetMouseButtonUp(0)){
placeone = false;
}
}
shouldn't that do it? Thanks for any help!
Answer by Wolfram · Jun 13, 2012 at 04:11 PM
Your problem is that you have multiple scripts, all reacting to the same Input.GetMouseButtonDown(0), and each spawning an object.
The easiest solution is to make the bool "placeone" static:
static bool placeone;
// your code
This way, there is only one instance of this bool, which is known (and identical) to all script instances of this class.
there is only one object that actually has the script to instantiate the planks. the others have no script right now to avoid that kind of error. that one object though is spawning more than one board if it collides with more than one object.
O$$anonymous$$, I misinterpreted the problem, but the solution is still valid. From the docs: "OnCollisionStay is called once per frame for every collider/rigidbody that is touching rigidbody/collider.".
that worked but i still dont understand why making it static fixes it if the only script that has the variable is the object that places the plank.
Hm, now that you mention it, you are right, it shouldn't make a difference - unless there is more than one instance of this script (or an object with this script attached) in your scene at runtime. Are you absolutely certain that is not the case?
You can verify that by putting your game in Play mode (in case you are instantiating other stuff on-the-fly), then right-click on the script in the Project tab and select "Find References in Scene". Now there should only be one object listed in the Hierarchy tab.
Your answer
![](https://koobas.hobune.stream/wayback/20220613072726im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How do I use OnCollisionStay? 2 Answers
Making a bubble level (not a game but work tool) 1 Answer
An OS design issue: File types associated with their appropriate programs 1 Answer