Instantiate error w. boolean

So i have a simple crafting script, if im inside of the “planks” collider and i press leftMousebutton it will set my boolean to active, and after that if i press “C” it will spawn (instantiate) an object. but when i start, it just spawns the object like every frame and i haven’t clicked anything… Help? (js)

~carlqwe

#pragma strict

private var ableSpawn : boolean;

var dass : GameObject;
var player : GameObject;

function Start ()
{
	ableSpawn = false;
}

function OnTriggerEnter (col : Collider) 
{
	if(col.tag == "planks" && Input.GetMouseButtonDown(0))
	{
		ableSpawn = true;
	}
}

function Update () 
{
	if(Input.GetKeyDown(KeyCode.C) && ableSpawn == true);
	{
		spawnObj();
	}
}

function spawnObj ()
{
	Instantiate(dass,player.transform.position, Quaternion.identity);
}

1 Answer

1

So without looking at your project I can only speculate what might be happening, so I’ll just kind of point some things out and how some of it helps. Your on trigger enter is the first point of worry. “Input.GetMouseButtonDown(0)” returns only once when you press the button. And OnTriggerEnter only fires once right when you enter the trigger area, so unless that happens simultaneously then it won’t occur, so I think the method you’re actually looking for is “OnTriggerStay”, read up on it and see if it suits you better.

And currently your “ableSpawn” variable will never not be true once you set it to true, so they’ll be able to spawn forever once they get the capability. So I don’t know if this will solve the problem you’re having, as it could be an issue with having it setup properly inside the editor, make sure that the collider is setup to be a trigger and things like that.