How to read values from another script?
Hi! I'm new here, new to c# and new to unity.
So, I'm want to create a 2D game and I started looking at the examples in unity hub. More precisely at the karting game example.
I want to read the user inputs from keyboard for the momment. I created an interface and a class similar to the ones from karting examples.
This:
using UnityEngine;
using System.Collections;
public interface IInput
{
bool moveRight { get; }
bool moveLeft { get; }
bool jump { get; }
bool jumpRight { get; }
bool jumpLeft { get; }
bool crouch { get; }
bool fire { get; }
}
And this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KeyboardInput : MonoBehaviour, IInput
{
public bool moveRight
{
get { return m_moveRight; }
}
public bool moveLeft
{
get { return m_moveLeft; }
}
public bool jump
{
get { return m_jump; }
}
public bool jumpRight
{
get { return m_jumpRight; }
}
public bool jumpLeft
{
get { return m_jumpLeft; }
}
public bool crouch
{
get { return m_crouch; }
}
public bool fire
{
get { return m_fire; }
}
bool m_moveLeft, m_moveRight, m_jump, m_jumpRight, m_jumpLeft, m_crouch, m_fire = false;
// Update is called once per frame
void Update()
{
if (Input.GetKey("right")){
//Move right
m_moveRight = true;
Debug.Log("Move right");
}
if (Input.GetKey("left"))
{
//Move left
m_moveLeft = true;
Debug.Log("Move left");
}
if (Input.GetKey("up"))
{
//Jump
m_jump = true;
Debug.Log("Jump");
if (Input.GetKey("right"))
{
//Jump right
m_jumpRight = true;
Debug.Log("Jump right");
}
if (Input.GetKey("left"))
{
//Jump left
m_jumpLeft = true;
Debug.Log("Jump left");
}
}
if (Input.GetKey("down"))
{
//Crouch
m_crouch = true;
Debug.Log("Crouch");
}
if (Input.GetKey("space"))
{
//Fire
m_fire = true;
Debug.Log("Fire");
}
}
}
For now it works fine. But I can't understand the way to read these values with another script. All examples I found are different. Nobody uses this approach. I'm not new to programming but I'm new to c# and unity. Please help me with a little example if possible.
I know that there is a easier way to get player input. But I'm curious about this method. How can I read theese variables from outside the script. I think this is a good method to create reuseable code. Like modules. And is a good method to add support for another controllers later on.
thanks!
Answer by mariusadrian · Apr 02, 2020 at 01:30 PM
After some research I found the answer in this thread. Its a little bit tricky. https://forum.unity.com/threads/struggling-to-understand-interfaces.471925/
thanks!
Your answer
Follow this Question
Related Questions
Displaying Text on Touch Event 0 Answers
Having trouble moving a GameObject to another scene and Transform it to a different position 0 Answers
unity visual studios not working properly 0 Answers
Finishing up my 2D quiz game [Last Problem] 0 Answers
Is there any way to increase score with UI when I destroy an object? 0 Answers