How to access classes in Unity 3D (C #)

0

I'm doing a 3D game on Engine Unity, a FPS to be more specific and taking advantage of this experience to learn programming in C #, the one I'm having in school.

But now I came across a problem, which I know is a simple solution, but since I did not study the language in depth, and only mastered the basics of C, I have no idea how to solve it.

I have, for this problem, 2 Scripts: The weapon and the character itself (FPS Controller). I want, through the script of the character to access the class "Pistol" that is the one of my script of the weapon, however, when I declare:

private Pistol arma;

It gives the following error:

  

"Assets / Standard Assets / Characters / FirstPersonCharacter / Scripts / FirstPersonController.cs (46,25): error CS0246: The type or namespace name 'Pistol' could not be found. ? "

I understand what this error is, I know what is wrong, but I do not know how that is correct.

PS: If necessary, I can put my code for better visualization of the error.

    
asked by anonymous 26.03.2016 / 21:13

2 answers

1

Look, I know only the method of instantiating one script with another, so you can access a Pistol method in Player for example.

//Pistol
using UnityEngine;
using System.Collections;

public class Pistol : MonoBehaviour {

//Instancia Pistol para ficar acessivel a outros Scripts
public static Pistol Instance;
private bool testa = false;

void Awake(){
    Instance = this;
  }
void Start(){
}
public void MetodoTeste(){
    testa = true;
  }
}


//Player
using UnityEngine;
using System.Collections;

public class Player : MonoBehavior{

//Instancie Player para poder receber Pistol
public static Player Instance;

void Awake(){
    Instance = this;
  }

void Start () {
    Pistol.Instance.MetodoTeste ();
  }
}

With this you access the 'Test Method' of the Pistol script through the Player script. When instanciating a script always declare it as public static Name Instance, so it becomes accessible to other scripts. Remember to instantiate the two scripts, Pistol and the Player (which received Pistol).

I hope it helps with what you need.

    
28.03.2016 / 06:45
1

From what I understand, you have the 2 scripts, Weapon and Player. If they are part of the same GameObject (your player / FPS Controller), you can get the script as follows:

private Pistol arma;
void Start(){
    arma = this.GetComponent<Pistol>();
}

Remembering that you say: "Pistol class" that is from my gun script "The class and script must have the same name, for example: if your class calls Pistol, the C # script has to call Pistol also, not Weapon.

Now, if your Pistol script is in another object, for example in the weapon itself, you can put a tag on it and in the script do the following:

private Pistol arma;
void Start(){
    arma = GameObject.FindWithTag("arma").GetComponent<Pistol>();
}

I think this will help. You'll be able to reference the outside classes. Good luck, hugs

    
12.04.2016 / 16:27