- Home /
How to access script from another script in an object?
So I am having trouble with getting some information in my game I am working on. Basically my player has a script called 'Stats', and it has allot of public static variables that I want my projectiles to access when they spawn.
My PlayerTests' Stats script: using UnityEngine; using System.Collections;
public class Stats : Component
{
public static float PlayerForce = 500.0f;
public static float PlayerMass = 500.0f;
public static float PlayerHull = 10.0f;
public static float PlayerSheild = 0.0f;
public static float GunFirerate = 5.0f;
public static float ShotSize = 1.0f;
public static float ShotSpeed = 50.0f;
public static float ShotDamage = 2.0f;
}
My Projectile Script:
using UnityEngine;
using System.Collections;
public class ProjectileSpawn : MonoBehaviour {
public static float damage;
void Start () {
GameObject Player = GameObject.Find ("PlayerTest");
Stats PlayerStats = Player.GetComponent<Stats>();
damage = PlayerStats.ShotDamage;
var heading = Player.transform.position - transform.position;
var distance = heading.magnitude;
var direction = heading / distance;
rigidbody2D.AddForce (direction * -PlayerStats.ShotSpeed);
}
I get these 3 errors:
Assets/Scripts/ProjectileSpawn.cs(12,38): error CS0176: Static member `Stats.ShotDamage' cannot be accessed with an instance reference, qualify it with a type name instead
Assets/Scripts/ProjectileSpawn.cs(20,64): error CS0176: Static member `Stats.ShotSpeed' cannot be accessed with an instance reference, qualify it with a type name instead
I fixed the Error cs0309 by adding : Component to the player scripts in the stats part
Answer by Landern · Jan 02, 2015 at 07:43 AM
You've made them static, you do not get an instance and access it that way, they live on the class not the instance.
You can access the fields anywhere by... as an example:
damage = Stats.ShotDamage;
rigidbody2D.AddForce (direction * -Stats.ShotSpeed);
Where Stats is the name of the class(remember, you made them static and not part of an instance(where you use new or instantiate it) and the normal property name.
And in this particular case, there isn't a good reason to have it derive from Component, because your implementation makes the static fields and exist that apply across the board.