This question already has answers here:
How to access a variable from another script in another gameobject through GetComponent?
(3 answers)
Closed 2 years ago.
so, my code;
Script one;
using System.Collections.Generic;
using UnityEngine;
public class mousePosTracker : MonoBehaviour
{
public Vector2 mousePos;
public void Update()
{
mousePos = Input.mousePosition;
Debug.Log(mousePos);
}
}
and script two;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class player : MonoBehaviour
{
void Update()
{
transform.Translate(// mouse position);
}
}
the code currently is pretty bare-bones, but I will fix that. so what I want to do is; I want to access the vector2 mousePos variable in script2, so that I can move the player based on the mouse position.
Make a reference on your Player script to your MousePosTrackerScript and use it.
One recommendation, use CamelCase on your class names.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public MouseousePosTracker posTracker = null; //attach it from your Editor or via script
void Update()
{
transform.Translate(posTracker.mousePos);
}
}
One easy way is to use the Find method.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private MousePosTracker mousePosTracker;
void Start(){
mousePosTracker = GameObject.Find("gameobject name which has the MousePosTrackerScript").GetComponent<MousePosTracker>()
}
void Update()
{
transform.Translate(mousePosTracker.mousePos);
}
}
If the gameobject has a tag you can use the FindWithTag method too.
Do like this in your 2nd script, always make sure your script has first letter in caps.
EDIT: if you do not want to give reference (drag&drop) in editor, use the below example. If you want it to be simpler without providing reference in the script, use Lotan's solution.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private MousePosTracker mouse;
void Start()
{
mouse = (MousePosTracker) GameObject.FindObjectOfType(typeof(MousePosTracker));
}
void Update()
{
transform.Translate(mouse.mousePos);
}
}
Related
I'm making a VR test and I've run into a problem and am not sure what to do. Unity keeps saying "type or namespace definition, or end of file expected unity" I am using someone else's code but I am following the tutorial. Here is my code
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VrRig : MonoBehaviour { }
public Transform headConstraint;
public Vector3 headBodyOffset;
{
// Start is called before the first frame update
void Start()
{
headBodyOffset = transform.position - headConstraint.position;
}
// Update is called once per frame
void Update()
{
transform.position = headConstraint.position + headBodyOffset;
transform.forward = Vector3.ProjectOnPlane(headConstraint.up,Vector3.up).normalized;
}
}
you are creating an empty class by having the curly brackets open and closed right after the class declaration. after you declare a code block with class members but never assign it to anything. If you put an opening curly bracket right after the class declaration and close it after all your members, it should work.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VrRig : MonoBehaviour
{
public Transform headConstraint;
public Vector3 headBodyOffset;
// Start is called before the first frame update
void Start()
{
headBodyOffset = transform.position - headConstraint.position;
}
// Update is called once per frame
void Update()
{
transform.position = headConstraint.position + headBodyOffset;
transform.forward = Vector3.ProjectOnPlane(headConstraint.up,Vector3.up).normalized;
}
}
For the past couple of days I've been trying to make a simple flappy bird game. At the moment, I'm trying to write some code that will make the score go up every time the player passes through two pipes. I'm getting an error though, and I'm not too sure how to fix it. This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Score : MonoBehaviour {
public static int score = 0;
private void Start() {
score = 0;
}
private void Update() {
GetComponent<UnityEngine.UI.Text>().text = score.ToString();
}
public void scoreUp() {
score++;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class AddScore : MonoBehaviour {
public Score score;
private void OnTriggerEnter2D (Collider2D collision) {
score.scoreUp(); // the line thats giving me problems
}
}
The error I'm getting is: error CS1061: Type Score does not contain a definition for scoreUp and no extension method scoreUp of type Score could be found.
This doesn't make sense to me. Unity says 'The CS1061 error is caused when you try to call a method or access a class member that does not exist.'. But as can be seen in the code above, I DO have a class called Score and I DO have a method inside it called scoreUp().
Furthermore, I have used this kind of code before (where I created a class, used it and its method inside another class) without any problem. So I'm really not sure what the problem is in this specific scenario.
I think a solution to your issue would be to make the "AddScore" Class a child of "Score".
To make it a child simply change
AddScore : MonoBehaviour -> AddScore : Score
What you can do also instead of using public scoreUp() make it Protected so only the child class can access it.
your code should be something like this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Score : MonoBehaviour {
public static int score = 0;
private void Start() {
score = 0;
}
private void Update() {
GetComponent<UnityEngine.UI.Text>().text = score.ToString();
}
protected void scoreUp() {
score++;
}
for the first bit and the second
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class AddScore : Score{
private void OnTriggerEnter2D (Collider2D collision) {
scoreUp();
}
}
There is a chance this is a duplicate, but I have tried and tried to get this to work and it's probably something simple.
I'm trying to get two scripts to interact on one object. I would like a basic generic physics script that will handle all the interactions for all my objects.
Script 1:
// Simple Player1
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player1 : MonoBehaviour
{
Physics physics_script;
void Start(){
physics_script = gameObject.GetComponent<Physics>();
}
// Update is called once per frame
void Update() {
physics_script.helloWorldFromAnotherScript();
}
}
Script 2:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Physics : MonoBehaviour
{
void Start(){
}
void Update() {
}
public void helloWorldFromAnotherScript()
{
Debug.Log("Hello world from player");
}
}
Edit:
I'm pretty sure the problem is here:
But I can't change it to save my life.
It should work.
Are you sure you have BOTH scripts added to the gameObject? At the image I only see player1, and I doubt if Physics it's added.
Elsewhere you can make physics_scripts public or serialize them(with [SerializeField]) and you will be able to drag'n'drop at the editor the script to the formfield. Thats allows you to not use the GetComponent<> at start.
Remember to delete start and update methods if you dont use them.
This question already has answers here:
How to access a variable from another script in another gameobject through GetComponent?
(3 answers)
In Unity, how can I pass values from one script to another?
(4 answers)
Closed 3 years ago.
I'm pretty new to C# and Unity, so sorry if my question is too simple.
I'm trying to create an easy Upgrade System made from text and button for each stat.
I made the Text script to show my "Attack Damage" stat, which worked. Now, I want to create a script Button so once that I click it my stat will go from (ex. 10 to 11) or anything. So my question is: how can I access variables from another script so that i can use them to be incremented by clicking the button?
I'll attach both the scripts, please try to explain as simple as you can, so that a newbie can understand. Thanks!
Attack Damage Text Script ( Keep in mind that in Player class the heroDamage is set to 10f)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AttackDamage : MonoBehaviour
{
public static float attackDamage = Player.heroDamage;
public Text attackDamageText;
// Start is called before the first frame update
void Start()
{
attackDamageText.text = ADButton.attack.ToString(); //here it was attackDamage.ToString() at first but i wanted to see if it works like that.
}
// Update is called once per frame
void Update()
{
}
}
Attack Damage Button Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ADButton : MonoBehaviour
{
public Button attackDamageButton;
public static float attack;
// Start is called before the first frame update
void Start()
{
attackDamageButton.onClick.AddListener(Update);
}
// Update is called once per frame
void Update()
{
attack = AttackDamage.attackDamage;
if (Input.GetMouseButtonDown(0))
attack++;
}
}
I guess my second code is wrong, but I don't know how can I modify it.
https://answers.unity.com/questions/1336162/how-to-reference-a-class-in-another-script-properl.html
This shows various possible methods.
But the simpler is reference by object.
like
public class AttackDamage : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
public void Method1()
{
// Do Something like Attack++;
}
}
public class ADButton : MonoBehaviour
{
public AttackDamage obj;
// Start is called before the first frame update
void Start()
{
obj.Method1();
}
}
Also in this case you need to assign the class AttackDamage in inspector on GameObject having ADButton script.
I'm working on 2D Unity game and I would like to know how we can display an image on my inventory when the player collide with an object. For exemple, if the player collide with a drumstick, the drumstick image appear on the inventory menu.
Best Regards.
Yacine TAZDAIT.
Method #1
There are many different ways to display an image. For example, you can have an image with an image component, and you switch the component on and off whenever you want the image to appear/disappear. You can do this using code similar to this:
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class Example : MonoBehaviour
{
public Image drumstick;
public void Start()
{
toggleDrumstick(); // This will toggle the drumstick. For example, if the drumstick is not being shown at the time, the drumstick will show on the screen. The opposite is true.
}
public void toggleDrumstick() {
drumstick.enabled = !drumstick.enabled;
}
}
Method #2
The code above is a great solution, but there is a more modular way to do it.
using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.
public class Drumstick : MonoBehaviour
{
public static bool enabled = this.image.enabled;
}
I recommend the method above. The reason for this is because every script can now access the drumstick's status. For example, your player script can do this.
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
void doSomething () {
Drumstick.enabled = true; // make the image appear.
}
}
For any of these methods to work, make sure your drumstick uses the image component.
EDIT:
To answer your question further, here is a way to implement method #2 in your code. In your player script, you can use OnCollisionEnter and the method above to make the drumstick appear.
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
void OnCollisionEnter (Collision collision)
{
if (collision.gameObject.tag == "drumstick") Drumstick.enabled = false;
}
}
For this to work, make sure that the drumstick has the tag "drumstick".