How do I call a variable from ScriptA into a function in scriptB?

Hi all,

I’m a having a bit of an issue calling a variable from ScriptA below into ScriptB to modify the score and display it on the screen.

I’m used to javascript but thought I’d try this in C# and now I’m a bit stuck.

all of the prefabs are children of a GameObject called Drops and have the PointValues script attached as a component.

I hope this is clear enough for you guys to help me out. I would appreciate any help you can provide. Thanks!

Please be specific in your answer as I’ve tried many of the answers to similar questions on this site and had no luck.

This is what I tried but couldn’t get to work.

MyAttempt at ScriptB (which Failed)

using UnityEngine;
using System.Collections;

public class DestroyObjectAddPoint : MonoBehaviour 
{

	int myScore = 0;

	public TextMesh scoretext;

	void OnTriggerEnter2D (Collider2D collisionObject)
	{
		var pointComponent : PointValues;
		poinyComponent = collisionObject.gameObject.GetComponent("PointValues");
		Destroy (collisionObject.gameObject);
		myScore = myScore + pointComponent.points;

		//Debug.Log ("My score is: " + myScore + " point(s)");

		scoretext.text = "Score: " + myScore;
	}
}

Here are the scripts.

ScriptA - Point Values


using UnityEngine;
using System.Collections;

public class PointValues : MonoBehaviour 
{
	public int points = 0;



	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}

ScriptB DestroyObjectsAddPoints


using UnityEngine;
using System.Collections;

public class DestroyObjectsAddPoints : MonoBehaviour 
{

	int myScore = 0;

	public TextMesh scoretext;

	void OnTriggerEnter2D (Collider2D collisionObject)
	{

		Destroy (collisionObject.gameObject);
		myScore++;

		//Debug.Log ("My score is: " + myScore + " point(s)");

		scoretext.text = "Score: " + myScore;
	}
}

a few things:

  • line 14, poinyComponent = collisionObject.gameObject.GetComponent("PointValues");

you have a typo. it should be pointComponent

  • line 15, Destroy (collisionObject.gameObject);

If I recall correctly, when you destroy the gameobject, the component goes with it.

rearranging your code and the typo looks like it should work:

var pointComponent : PointValues;
pointComponent = collisionObject.gameObject.GetComponent("PointValues");
myScore = myScore + pointComponent.points;
Destroy (collisionObject.gameObject);
 
Debug.Log ("My score is: " + myScore + " point(s)");
 
scoretext.text = "Score: " + myScore;

You might also add an if statement to see if pointComponent is null, to see if it’s actually getting the right component