Shared variables in Unity 3D [duplicate] - c#

This question already has answers here:
Accessing a variable from another script C# [duplicate]
(3 answers)
Closed 6 years ago.
I have 2 c# scripts in my game. On of them is in my "main player object" and the other script is in "my main camera". I want to declare a float variable in the script of my main player, and in every game second i want to record the x position of my player in that variable and at the same time passing this value to the my main camera's script and assigning this value into the x position of my main camera in every game second. How can I pass a variable to a script from another one ? Or how can i create a variable which can be used by any script in my game ?

There's an answer here that explains this problem in great detail, but the simplest way that is included in that answer would be to do something like the following:
public class Speed: MonoBehaviour
public float speed;
// maybe you want restrict this to have read access, then you should use a property instead
And then in other scripts:
GameObject gameObject = GameObject.Find ("Some object");
Speed theSpeed = gameObject.GetComponent <Speed> ();
float mySpeed= theSpeed.speed;

Related

Instantiated Object sometimes gives NullReference but sometimes not [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 months ago.
So i am trying to make a simple gameobject saving system in Unity.
Whenever i place an cube i enter it in a GameObject called currentCube
GameObject currentCube = new GameObject();
currentCube = Instantiate(CubeBlue, placeLocation, new Quaternion());
This places my cube all good and well. Then just for debugging i check if the currentCube actually has the just placed Cube
print(currentCube.transform.position);
This does indeed give the location of my newly placed Cube. But then i try to add the cube to a List (also tried with an array)
cubes.Add(currentCube);
But then i get a NullReferenceException
NullReferenceException: Object reference not set to an instance of an object
And then with the Script filename and the location line of where i put the "cubes.Add(currentCube;)"
EDIT:
Also in my part above the void start i have stated
private List<GameObject> cubes;
Looks like your List is not getting Initialized. Try
private List<GameObject> cubes = new List<GameObject>();

Unity c# how to properly use GetComponent [duplicate]

This question already has answers here:
How to access a variable from another script in another gameobject through GetComponent?
(3 answers)
Closed 25 days ago.
I am in no way a coding novice but I just picked up unity and I'm trying "get it"
My question involves this code. it is not part of an active project. it is simply an attempt to understand the system
private SpriteRenderer beans2;
public Sprite beanimmage;
// Start is called before the first frame update
void Start()
{
beans2 = gameObject.GetComponent<SpriteRenderer>();
beans2.sprite = beanimmage;
}
from what I understand this code allows me to manipulate the SpriteRenderer of the game object this code is attached to by assigning it to beans2 and then changing the Sprite of beans2 to beanimmage and works fine in the system
My question is -
Is their a way to assign beans2 to the spriterenderer of a diffident game object? The object i have this code attached to is just a game object called test is their a way to assign the beans2 variable to the SpriteRenderer of my test2 object instead ?
something like this ?
beans2 = test2.gameObject.GetComponent<SpriteRenderer>();
beans2 = gameObject.test2.GetComponent<SpriteRenderer>();
The GetComponent() Function is apart of every gameobject so to get components on other gameobjects you need to reference that gameobject in a variable, something like this:
public GameObject test2;
private SpriteRenderer test2Renderer;
public Sprite beanImage;
void Awake()
{
test2Renderer = test2.GetComponent<SpriteRenderer>();
test2Renderer.sprite = beanImage;
}
Alternatively, you can just get the component of the test2 object from the inspector because you are using public variables. To do this make a sprite renderer variable field and make it public so it is shown in the inspector, then drag the test2 object into the field and it will automatically get the sprite renderer component off that object.
Finally, you could also just do this with one field. This method would be used when you only want to access the GameObject and nothing else:
public GameObject test2;
public Sprite beansImage;
void Awake
{
test2.GetComponent<SpriteRenderer>().sprite = beansImage;
}
Any way works and you should do it the second way if you want to work with public variables and rely on the inspector but if you only need the gameobject then go with method 3. Method 1 is probably the best way to do it so you can change the sprite later if you want.

How do you create a default player for an enemy AI script in Unity? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
In Unity (C#), why am I getting a NullReferenceException and how do I fix it? [duplicate]
(1 answer)
Closed 1 year ago.
I have an enemy AI script working that basically follows my player. Right now I have a "public GameObject player" that I have to assign manually by dragging my player prefab onto the slot. But I want to have a lot of enemies in the scene, so I don't want to have to do this manually for each one. How Can I give the EnemyController script a default player to follow?
I have a PlayerManager which I use to pass the position of my player to the enemy with:
public class EnemyController : MonoBehaviour
{
Transform target;
// Start is called before the first frame update
void Start()
{
target = PlayerManager.instance.player.transform;
}
That part works fine. So my thinking was, just make a public variable for the player like this:
public GameObject player = PlayerManager.instance.player;
But that didn't work. I got this error: "NullReferenceException: Object reference not set to an instance of an object"
Thank you so much for any help you can provide!
With public GameObject player = PlayerManager.instance.player; your field is initialized before the call of EnemyController's constructor, and you provided no control over the value / definition state of PlayerManager.instance.player (PlayerManager or instance or player which can be null and is null in your case). So it's "too early" to use it.
Instead, you can use the event playerJoinedEvent in the PlayerInputManager to assign the enemy to the played which just joined with an event handler, which checks that PlayerManager and instance and player are not null and then assign the player to the target.

How can I move an object towards another object in Unity3D? [duplicate]

This question already has answers here:
Moving an object with vector3.MoveTowards
(2 answers)
Closed 4 years ago.
I have a cube that I want to always be moving towards my player. I've tried several solutions over the course of a few hours, but none of them have worked. My current script looks like this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fol : MonoBehaviour {
// Use this for initialization
void Start () {
}
public GameObject Player;
// Update is called once per frame
void Update ()
{
Vector3.MoveTowards(Player.transform.position.x, Player.transform.position.y, Player.transform.position.z, 1);
}
}
This script is a child of the object that I want to move towards my player.
Nothing has ever compiled. The only error for this script is:
Assets/fol.cs(16,11): error CS1501: No overload for method MoveTowards takes 4 arguments
So, once I remove the 1 it ends up with:
Assets/fol.cs(16,11): error CS1502: The best overloaded method match for UnityEngine.Vector3.MoveTowards(UnityEngine.Vector3, UnityEngine.Vector3, float)' has some invalid arguments
and
Assets/fol.cs(16,49): error CS1503: Argument #1 cannot convert float expression to type UnityEngine.Vector3
In your MoveTowards the first position given should be the position of the object you need to move, then the second should be the position of the goal, with the third argument being the movement increment. As #Ruzihm suggests this is a duplicate of Moving an object with Vector3 and you'll find a great info to resolve this there. Also check out the unity API.

How to edit variables in another game object.(Unity C#) [duplicate]

This question already has answers here:
Accessing a variable from another script C# [duplicate]
(3 answers)
Closed 4 years ago.
Do keep in mind that I am not good at Unity.
I have a Game Object with a variable called hp. I have another Game Object with a trigger collider. When the trigger runs, I want it to edit the variable hp but I don't know how to edit variables from another game object.
Please may I have some help.
In Unity, the OnTriggerEnter(Collider other) function is called when a collision is triggered.
In argument of the function, you get a collider named other, which is a reference to the collider script your object collided with. As any script in unity, you can call other.gameObject to retrieve the colliding gameObject. From then, you can use the GetComponent function to find a script on the object.
In your case, lets say you have an object on which you put this script:
public class Player : MonoBehaviour {
public float hp;
}
You need to create another script that handles the collision. Put this on the object that collides with your player
public class Obstacle : MonoBehaviour
{
public float damages;
private void OnTriggerEnter(Collider other)
{
if(!other.gameObject.HasComponent<Player>())
return;
var player = other.gameObject.GetComponent<Player>();
player.hp -= damages;
}
}

Categories