I am trying to create an Event Trigger for a GameObject that involves updating a specified field from another GameObject. For example, I have a GameObject named GameData with a public int field named modeStyle and another public int named initialHealth. I then want an event trigger to call an outside function that takes either one of these int fields as a parameter to update the GameData. Is there a specific way for this to be done? I have yet to determine the proper way to code this.
Sort of like this, even though it’s wrong:
public void UpdateGameData(GameData.mode as int)
{
Debug.Log("Mode Style:" + mode);
}
Edited in response to your comment.
public class GameData : Monobehaviour
{
public int gameScoreA;
public int gameScoreB;
public void UpdateGameScore(int gameScoreToUpdate int newScore)
{
if (gameScoreToUpdate == 1)
{
gameScoreA = newScore;
}
if (gameScoreToUpdate == 2)
{
gameScoreB = newScore;
}
}
}
_
public class SomeScript : MonoBehaviour
{
public GameObject gameDataGO;
private void Start()
{
int newScoreToAdd = 100;
gameDataGO.GetComponent<GameData>().UpdateGameScore(1, newScoreToAdd);
}
}
_
_
Your terminology is a little confusing and so is your architecture.
_
“I have a GameObject named GameData” I’m going to assume you mean you have a script called GameData attached to a GameObject. Hopefully I understood what you are trying to do.
_
Ok… so there’s a few ways you can go about doing this.
_
-
use a static class or method.
namespace MyGame.Managers
{
public static class MyStaticClass
{
public static int gameScore { get; private set; )
public static void UpdateGameScore(int newScore)
{
gameScore = newScore;
}
}
}
_
This would allow you to call the method UpdateGameScore() without actually having a reference to it.
_
using MyGame.Managers;
namespace MyGame.Player
{
public class PlayerManager : MonoBehaviour
{
public void Start()
{
int newScore = 50;
MyStaticClass.UpdateGameScore(newScore);
}
}
}
_
2) use some kind of reference
namespace MyGame.Managers
{
public class GameManager : MonoBehaviour
{
public int gameScore { get; set; }
}
}
_
namespace MyGame.Player
{
public class Player : Monobehaviour
{
public GameObject gameManager;
public void Start()
{
gameManager.GetComponent<GameManager>().gameScore = 100;
}
}
}
_
3) Reference the script and invoke a method.
namespace MyGame.Managers
{
public class GameManager : MonoBehaviour
{
public int gameScore { get; private set; }
public void UpdateGameScore(int pointsToAdd)
{
gameScore += pointsToAdd;
}
}
}
_
namespace MyGame.Player
{
public class Player : Monobehaviour
{
public GameObject gameManager;
public void Start()
{
int pointsToAdd = 50;
gameManager.GetComponent<GameManager>().UpdateGameScore(pointsToAdd);
}
}
}