Get value from another script
So. Dispite using unity for a long time i never really written any code... But used a visual scripting tool.... So recently i decided to move to actual scripting because visual was too damn expensive.
So i was wondering if you could help me out with this: I want to set the value of
"public int PlayerScoreKeep"
from another script called "Coin.cs"
As you may of guessed i am trying to make a score keeper thing
If you don't mind help would be greatly appreciated!
Coin.cs: (The one i want to send the value to the other script)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Coin : MonoBehaviour
{
public int PlayerScoreKeep;
void OnTriggerEnter(Collider col)
{
PlayerScoreKeep = PlayerScoreKeep + 1;
Destroy(gameObject);
}
}
Score.cs (The one that i want to get the value)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
public int PlayerScoreKeep;
public Text Scorekeep;
void Start()
{
}
}
Okay thank you!
(Sorry if this was hard to understand my English is not the best)
Answer by MT369MT · Aug 09, 2018 at 09:16 PM
Hi, create a new Coin variable and assign it in Start using FindObjectOfType like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
public int PlayerScoreKeep;
public Text Scorekeep;
public Coin Coin;
void Start()
{
Coin = GameObject.FindObjectOfType<Coin>();
}
void Update()
{
PlayerScoreKeep = Coin.PlayerScoreKeep;
}
}
Your answer
Follow this Question
Related Questions
How To Connect 2 Scripts So You Can Communicate The Variables?? 0 Answers
Health pickup script issue -1 Answers
Script error and no Variables showing 0 Answers
How to make brake car ? 2 Answers