Alright so im basically creating a MoneySystem in my game where when your player collides with the object “Money”, and then money is destroyed, and then the variable CurrentMoney, which is in a seperate script (called PlayerStats), is increased by the variable MoneyAmount. Now my problem is, when I collide with money, the console comes up saying “Contact was Made”, but then under it there is an error saying "you are trying to create a monobehaviour using the ‘new’ keyword. This is not aloud, monobehaviour can only be added using addcomponent()… What is going on?!?
Here is my code
Money script which is located under the object “Money”
#pragma strict
public var MoneyAmount : int = 50;
private var otherclass : PlayerStats;
function OnTriggerEnter (col : Collider) {
if (col.gameObject.tag == "Player") {
Debug.Log("Contact was made");
otherclass = new PlayerStats();
otherclass.CurrentMoney = otherclass.CurrentMoney + MoneyAmount;
}
}
PlayerStats script which is located under my First Person Controller (player)
So lets go right back to basics here. The logic of you code is wrong to start with. So the other answers fixing your errors are just giving you code that compiles, but does the wrong thing. Here is an example of correctly structured code. Note I don’t normally do JavaScript, you may need to mess with the syntax slightly.
Locate this script on the money object
#pragma strict
public var MoneyAmount : int = 50;
function OnTriggerEnter (col : Collider) {
if (col.gameObject.tag == "Player") {
Debug.Log("Contact was made");
var otherclass = col.gameObject.GetComponent(PlayerStats);
otherclass.CurrentMoney += MoneyAmount;
}
}
Note that this question “How do I access a variable on another script” is the most commonly asked question on UA. The steps are as follows:
Get a reference to the GameObject containing the script
Your class PlayerStats is inheriting form Monobehaviour, as all scripts do by default. Remove the Monobehaviour extension in the PlayerStats class to get the new PlayerStats() line to run.
Alternatively, if you want the Monobehaviour parent class for PlayerStats, use