How do I call a method from another script?
I have been searching the web for a long time, but I can't find an answer that I can use. (This is my first Unity game ever. I'm following a course on youtube and copy what he does. Just for learning how to do things. So I tried to make my own ammo system, where I almost did the same as he did with health(I have removed health, so it's easier to read.), and I finally got it to work (along with some errors I had to fix by making this script a little strange, which you might notice).). The method in the player script is called "UseAmmo", and is supposed to decrease my ammo by. The problem is that I don't know how to call it from the weapon script when I shoot. Please help me :D Here's my player script:
using UnityEngine; using System.Collections;
public class Player : MonoBehaviour {
[System.Serializable]
public class PlayerStats
{
[SerializeField]
private StatusIndicator statusIndicator;
public static int WeaponDamage = Random.Range(1, 1);
public int maxAmmo = 200;
public int startAmmo = 50;
private int _curAmmo;
public int curAmmo
{
get { return _curAmmo; }
set { Mathf.Clamp(value, 0, maxAmmo); }
}
public void Init()
{
_curAmmo = startAmmo;
}
public void UseAmmo(int minAmmo)
{
_curAmmo -= minAmmo;
if (_curAmmo == 0)
{
nullifyDamage();
}
// statusIndicator.SetAmmo(curAmmo, maxAmmo);
}
public void GetAmmo(int plusAmmo)
{
_curAmmo += plusAmmo;
if (_curAmmo > 0)
{
createDamage();
}
statusIndicator.SetAmmo(curAmmo, maxAmmo);
}
public void nullifyDamage()
{
WeaponDamage = 0;
}
public void createDamage()
{
WeaponDamage = Random.Range(20, 50);
}
}
public PlayerStats stats = new PlayerStats();
[SerializeField]
private StatusIndicator statusIndicator;
void Start()
{
stats.Init();
if (statusIndicator == null)
{
Debug.LogError("No status indicator referenced on Player");
}
if (statusIndicator != null)
{
statusIndicator.SetAmmo(stats.curAmmo, stats.maxAmmo);
}
}
//More script down there, which doesn't matter
And now a little bit of my weapon script (which is working fine besides the problem I mentioned). I have also removed the parts of the script that didn't matter:
using UnityEngine; using System.Collections;
public class Weapon : MonoBehaviour { void Shoot() { // I would like to call the method here. } // More script
}
Answer by Maemmo · Nov 06, 2015 at 04:22 PM
Sorry, it turned out to look quite strange in the last script, but I hope you get what means.