Cant access variable with GetComponent<>();

I read some help but i cant access variable on my other script.`using UnityEngine;
using System.Collections;

public class ShootMove : MonoBehaviour {

// Use this for initialization
void Start () {
	Networking123.realPos = Move.hlaven.transform.position;
	if (Move.facingRight == false) {
		rigidbody2D.velocity = new Vector3 (15f, 0, 0);
	} else {
		rigidbody2D.velocity = new Vector3 (-15f, 0, 0);
	}
}

// Update is called once per frame
void Update () {

}
void OnCollisionEnter2D (Collision2D col){
	if (col.gameObject.tag == "Player") {
		GameObject resp = col.gameObject;
		Respawning a = resp.GetComponent<Respawning>();
		a.resptime = Time.realtimeSinceStartup;
		PhotonNetwork.Destroy (col.gameObject);
		PhotonNetwork.Destroy (this.gameObject);
	} 
	else {
		PhotonNetwork.Destroy (this.gameObject);
	}
}

}`

I have my variable resptime in other script as “public float resptime = 0f;”
Its on other object and i want to write to it when its colide with my player. When you can please write the example of code to do this :slight_smile: i dont speak english very well so some references are usefull but something is not understand for me.

Thanks Dejvidus

As per your error you need to call resptime this way :

Respawning.resptime = Time.realtimeSinceStartup;

you dont need to use GetComponent or even to query the game object

Your code could be :

void OnCollisionEnter2D (Collision2D col){
     if (col.gameObject.tag == "Player") {
         Respawning.resptime = Time.realtimeSinceStartup;
         PhotonNetwork.Destroy (col.gameObject);
     } 
     PhotonNetwork.Destroy (this.gameObject);
 }

That is because resptime is declared static which means you can access it directly and it is not tied to an instance of the Respawning class.

A few consideration as a bonus :

  • Do not name your classes using a Verb like “Respawning”, it is misleading for the reader
  • Avoid static fields on classes that will be instanciated, in some very rare case you might need that but for all other cases there probably exist a better solution
  • Do not duplicate code like PhotonNetwork.Destroy (this.gameObject); you had one more operation for the else and it will bring tons of errors when you will come back to this code to add new features.