- Home /
Count Value of Object in triggerzone,Checking value of Item ontrigger
Hi Guys ! I'm new and need some help. I made a Store and want to count/read out a value of different items (for example banana: 5$, TV 500$) when they are thrown into a trigger zone (Box Collider trigger). Can someone help me out ?,Hi guys. I'm new here and got a problem. I want to give different items (gameobjects), different values (for example a banana 5$ and a TV 500$) and read out/count this values, if the item is thrown into a trigger zone. I don't know how to do it, can someone help me out ?
Answer by Llama_w_2Ls · Apr 05, 2021 at 02:40 PM
Do you have a script assigned to the objects containing their price? If not, you should create a script that looks like this at least:
public class Value : MonoBehaviour
{
public float price;
}
Then, in the inspector, if you assign the script to a TV, you can set the price
property to 500. Same for a banana as well.
Finally, you'll need a script on the trigger collider that gets the object that collided with it. For example:
public class ObjectTrigger : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
Value valueScript = other.gameObject.GetComponent<Value>();
// Gets the price of the object that entered the trigger zone
Debug.Log(valueScript.price);
}
}
Maybe you can help again. I used your code and everything worked perfect. Now i want to update my Scoretext (UI) with the price instead of showing it in the console. I used this code:
public class ObjectTrigger : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
Value valueScript = other.gameObject.GetComponent<Value>();
ScoreText.moneyamount += valueScript.price;
}
}
I tried a lot, but don't know why it isn't working. When i change the "ScoreText.moneyamount += valueScript.price;" to "ScoreText.moneyamount += 1;" it updates my UI, so the UI thing works.
The field valueScript.price
is a float and can be a decimal number. I don't know the 'type' of ScoreText.moneyamount
but if it is an int, then you can't add a float to an int.
You'll either need to change ScoreText.moneyamount
to a float, or cast valueScript.price
to an int, which rounds it. $$anonymous$$g:
ScoreText.moneyamount += (int)valueScript.price;
Answer by timbonn · Apr 05, 2021 at 02:56 PM
Thank you ! That looks so much simpler than anything that I tried.
Have to code more by myself to learn it.