Variables in script do not show in Inspector (Unity) - c#

I'm trying to learn how to use Unity and following online tutorials but I am currently having a problem that I don't understand how to fix.
I have a Sprite in my scene and I have attached a script to it however in the Inspector it shows the script is there but I cannot see the variables inside? I had this problem previously and it sorted itself out.
What is the cause of this problem/how do I fix it?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpaceShip : MonoBehaviour {
public float speed = 30;
public GameObject theBullet;
private void FixedUpdate()
{
float horzMove = Input.GetAxisRaw("Horizontal");
GetComponent<Rigidbody2D>().velocity = new Vector2(horzMove, 0) *
speed;
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Jump"))
{
Instantiate(theBullet, transform.position, Quaternion.identity);
}
}
}

Edit: The problem was solved by reimporting.
You either need to declare the variables as Public or [SerializeField] for member variables to appear in the inspector. Note that by declaring something as public allows access to the variable from outside the class (from other scripts/classes for example). By default, private is assigned to member variables.
Example:
public class testscript : MonoBehaviour
{
public int foo; // shows up in inspector
[SerializeField] private int bar; // also shows up while still being private
void Start()
{
}
}

Not is a problem, You forget to do something surely.
It is common at first with Unity.
Start again.
In the scene create a new GameObject and add you script.
If the inspector shows not variable:
The varible do not is public (false, if is public in you script)
There is some syntax error in the script!
or
You were not adding the correct script to the GameObject.
There are not many secrets to that, if all is well enough that the variable is public and this outside of a method of the script so that it is seen in the inspector.
One tip, do not use a GetComponent or Instantiate inside a FixedUpdate or Update because they are expensive, save the Rigidbody2D in a variable in the Start and then use it.
Sorry for my English and good luck.

Related

How to access the value of cinemachine's camera distance in Unity / C#?

I'm working on Unity/C# now and I'm stuck with accessing CinemachineVirtualCamera's camera distance value in the script. What I'm trying to do is change the value of camera distance in the body section.
First of all, how can I access the CinemachineVirtualCamera component in this game object? The MoveScript is what I attached to a player game object, and I want to zoom out the camera depending on the player's movement. Since the game I'm making is small, I won't make other .cs files.
I wrote
public class MoveScript: MonoBehaviour
{
private GameObject camObj;
void Start()
{
camObj = GameObject.Find("Vertical Follow Camera");
camObj.GetComponent<CinemachineVirtualCamera>(); // <- but I get error saying, The type or namespace name 'CinemachineVirtualCamera' could not be found
}
}
I also read this document and I think the m_CameraDistance is what I'm looking for but how can I access that value?
For anyone else who wondering
GetComponent<CinemachineVirtualCamera>()
.GetCinemachineComponent<CinemachineFramingTransposer>()
.m_CameraDistance
As stated in the linked document, these classes are in Cinemachine namespace. To access the classes you have to either add
using Cinemachine;
to the beginning of your script or change your script to
public class MoveScript: MonoBehaviour
{
private GameObject camObj;
void Start()
{
camObj = GameObject.Find("Vertical Follow Camera");
camObj.GetComponent<Cinemachine.CinemachineVirtualCamera>();
}
}
And as for accessing the m_CameraDistance variable, HuySora already answered that part
Try this and don't forgot to mention namespace
public class MoveScript: MonoBehaviour
{
private CinemachineVirtualCamera virtualCamera;
private GameObject camObj;
void Start()
{
camObj = GameObject.Find("Vertical Follow Camera");
virtualCamera = camObj.GetComponent<CinemachineVirtualCamera>();
float f = virtualCamera.m_CameraDistance;
}
}

Why does C# Not see the variable in another Script when Using GetComponent? C#

So I have a CharacterController Class that just deals with User inputs and If the player is hit by a bullet and reduces the Health of that Character. I need to use this Health Value in another Script so Have used the following code to try this however I get a CS01061 as it says it cannot find the Health variable.
Character Controller Class Variables:
public class CharacterController : MonoBehaviourPunCallbacks
{
public float MovementSpeed = 2;
public float JumpForce = 5;
public float Health = 100f;
public float height = 10;
public static GameObject LocalPlayerInstance;
Here is the code for the PlayerManager Class that needs Health from above:
//Gloabl Variables
public GameObject ActualPlayer;
public CharacterController Controller;
public float Health;
public void Awake()
{
ActualPlayer = GameObject.Find("Player");
Controller = ActualPlayer.GetComponent<CharacterController>();
Health = Controller.Health;
......
Player is a prefab that is a GameObject that has been initialised by Photon and has the CharacterController script as a component. Why can't unity see that the script has a health variable?
Are you sure it is looking for the correct type and not maybe one with the same name but from a different namespace?
Unity itself already has a built-in type named CharacterController in the namespace UnityEngine so most probably your second script is using that type since on the top you will have a
using UnityEngine;
Make sure you are referencing the correct one in your script.
You could e.g. put yours into a specific namespace like
namespace MyStuff
{
public class CharacterController : MonoBehaviourPunCallbacks
{
...
}
}
and then in your other script explicitly use
public MyStuff.CharacterController Controller;
and
Controller = ActualPlayer.GetComponent<MyStuff.CharacterController>();
Health = Controller.Health;
Besides that remember that float is a value type, not a reference, so most probably you storing that value in a field in your second script is not what you want to do ;)
rather always simply access the Controller.Health instead.

Unity C#: type error referencing float from another script

I'm new to Unity, and although I've looked this up a million times, I can't get my script to stop erroring. I am trying to reference a public float (attached to a different object) in a new script - which is simple, I know. I have tried various methods, but this is what I have so far. I keep getting the error that the float (currentHealth) cannot be implicitly converted to 'Health', which I understand but cannot seem to fix. What am I doing wrong?
public class sugarGenerator : MonoBehaviour
{
public GameObject sugar;
public GameObject Insulin;
public Transform generationPoint;
public float distanceBetween;
Health PlayerHealth;
// Update is called once per frame
public void Awake ()
{
GameObject.FindWithTag("Main_Girl_0");
PlayerHealth = GetComponent<Health>().currentHealth;
}
}
Based on my comment:
PlayerHealth is not a float, it is Health. You cannot assign a float (the type of currentHealth) to a Health.
I'm not familiar with Unity, but perhaps you meant to do:
PlayerHealth = GetComponent<Health>();

How to fix "the object of type 'GameObject' has been destroyed, but you are still trying to access it" error in Unity?

I'm creating a 2.5D fighting game in Unity with C#. Currently, I'm trying to make a bumper appear around the player and disappear after a set amount of time. I've managed to make the bumper appear and disappear once, but after that, when I try to make the bumper appear again, Unity has an error for me: "The object of type 'GameObject' has been destroyed but you are still trying to access it."
I've tried using the "instantiate" and "destroy" commands, following a tutorial by "Brackeys" on 2D shooting. After also following some questions on forums about the same issue, I've altered my code again, but the problem persists.
The firePoint is an empty object, from where the BumperPrefab is instantiated.
using UnityEngine;
public class weapon: MonoBehaviour
{
public Transform firePoint;
public GameObject BumperPrefab;
public float lifetime = 0.2f;
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
attack();
}
}
void attack()
{
BumperPrefab = (GameObject) Instantiate(BumperPrefab, firePoint.position, firePoint.rotation);
Destroy(BumperPrefab, lifetime);
}
}
I expect the GameObject "BumperPrefab" to appear, stick around for 0.2 seconds and disappear. I should be able to repeat that as many times as I want, but what actually happens is that I can do this only once and then the error "The object of type 'GameObject' has been destroyed but you are still trying to access it" shows up and I can't make the BumperPrefab appear again.
Any help is much appreciated!
using UnityEngine;
public class weapon: MonoBehaviour
{
public Transform firePoint;
public GameObject BumperPrefab;
public float lifetime = 0.2f;
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
attack();
}
}
void attack()
{
var bumper = (GameObject) Instantiate(BumperPrefab, firePoint.position, firePoint.rotation);
Destroy(bumper, lifetime);
}
Right now you're overwriting your public field containing the prefab object with your instantiated object, then destroying it. Set the instantiated object as a variable and you should be fine.
The problem is that in your code you don't care about is your GameObject exist. So for example if (for some reason) the object BumperPrefab will not be created, Destory() will try to act on null.
You can try add to BumperPrefab script bumper.cs with:
float lifetime = 0.2f;
private void OnEnable()
{
Desroy(this, lifetime)
}
problem is you are destroying BumperPrefab
when you Instantiate a new GameObject you should add it to the local variable like this
var newbumper = (GameObject) Instantiate(BumperPrefab, firePoint.position,firePoint.rotation);
and you must destroy your local variable which contains newly created gameObject
Destroy(newbumper , lifetime);

How do I pass variable from one script to another C# Unity 2D?

For example I have a variable (public static float currentLife) in script "HealthBarGUI1" and I want to use this variable in another script.
How do I pass variable from one script to another C# Unity 2D?
You could do something like this, because currentLife is more related to the player than to the gui:
class Player {
private int currentLife = 100;
public int CurrentLife {
get { return currentLife; }
set { currentLife = value; }
}
}
And your HealthBar could access the currentLife in two ways.
1) Use a public variable from type GameObject where you just drag'n'drop your Player from the Hierarchy into the new field on your script component in the inspector.
class HealthBarGUI1 {
public GameObject player;
private Player playerScript;
void Start() {
playerScript = (Player)player.GetComponent(typeof(Player));
Debug.Log(playerscript.CurrentLife);
}
}
2) The automatic way is achieved through the use of find. It's a little slower but if not used too often, it's okay.
class HealthBarGUI1 {
private Player player;
void Start() {
player = (Player)GameObject.Find("NameOfYourPlayerObject").GetComponent(typeof(Player));
Debug.Log(player.CurrentLife);
}
}
I wouldn't make the currentLife variable of your player or any other creature static. That would mean, that all instances of such an object share the same currentLife. But I guess they all have their own life value, right?
In object orientation most variables should be private, for security and simplicity reasons. They can then be made accessible trough the use of getter and setter methods.
What I meant by the top sentence, is that you also would like to group things in oop in a very natural way. The player has a life value? Write into the player class! Afterwards you can make the value accessible for other objects.
Sources:
https://www.youtube.com/watch?v=46ZjAwBF2T8
http://docs.unity3d.com/Documentation/ScriptReference/GameObject.Find.html
http://docs.unity3d.com/Documentation/ScriptReference/GameObject.GetComponent.html
You can just access it with:
HealthBarGUI1.currentLife
I'm assuming that HealthBarGUI1 is the name of your MonoBehaviour script.
If your variable is not static and the 2 scripts are located on the same GameObject you can do something like this:
gameObject.GetComponent<HealthBarGUI1>().varname;
//Drag your object that includes the HealthBarGUI1 script to yourSceondObject place in the inspector.
public GameObject yourSecondObject;
class yourScript{
//Declare your var and set it to your var from the second script.
float Name = yourSecondObject.GetComponent<HealthBarGUI1>().currentLife;
}
TRY THIS!
//Drag your object that includes the HealthBarGUI1 script to yourSceondObject place in the inspector.
public GameObject yourSecondObject;
class yourScript{
//Declare your var and set it to your var from the second script.
float Name = yourSecondObject.GetComponent<HealthBarGUI1>().currentLife;

Categories