KOpp0t
March 5, 2022, 10:36am
1
I know this question gets asked a lot here, but I have been reading for a while and still dont know how to do it…
I am using Unity Standerd Asset FirstPersonController script, and it has a float called “m_RunSpeed”
I hjave made a script called StatusBars that has a variable called “SprintSpeed”.
I want the FirstPersonController script value of “m_RunSpeed” to be equal to “SprintSpeed”.
Here is my StatusBars script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class StatusBars : MonoBehaviour
{
public Slider HealthSlider;
public Slider HungerSlider;
public Slider EnergySlider;
public float HP;
public float Hunger;
public float Energy;
public float WalkDecreaseTime;
public float SprintDecreaseTime;
private float DecreaseTime;
public float EnergyIncreaseTime;
public float EnergyDecreaseTime;
public bool Increasing;
public bool isSprinting;
private float SprintSpeed;
public float DefaultSprintSpeed;
public float DecreasedSprintSpeed;
// Start is called before the first frame update
void Start()
{
HealthSlider.value = HP;
HungerSlider.value = Hunger;
EnergySlider.value = Energy;
DecreaseTime = WalkDecreaseTime;
SprintSpeed = DefaultSprintSpeed;
}
// Update is called once per frame
void Update()
{
if(Input.GetKey(KeyCode.LeftControl))
{
isSprinting = true;
}
else
{
isSprinting = false;
}
if(isSprinting == true)
{
DecreaseTime = SprintDecreaseTime;
SprintSpeed = DefaultSprintSpeed;
}
else
{
DecreaseTime = WalkDecreaseTime;
}
if(Energy >= 0)
{
SprintSpeed = DecreasedSprintSpeed;
}
else
{
SprintSpeed = DefaultSprintSpeed;
}
if(Energy < 100 && isSprinting == false)
{
Energy = Energy += EnergyIncreaseTime * Time.deltaTime;
}
if(Energy > 0 && isSprinting == true)
{
Energy = Energy -= EnergyDecreaseTime * Time.deltaTime;
}
Hunger = Hunger -= DecreaseTime * Time.deltaTime;
Refresh();
}
public void Refresh()
{
HealthSlider.value = HP;
HungerSlider.value = Hunger;
EnergySlider.value = Energy;
}
}
Please assist
KOpp0t
March 5, 2022, 10:38am
2
for further detail.
Here is the FirstPersonController script that i am using
Line 16 has the refrencing for “m_RunSpeed”
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
#pragma warning disable 618, 649
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (AudioSource))]
public class FirstPersonController : MonoBehaviour
{
[SerializeField] private bool m_IsWalking;
[SerializeField] private float m_WalkSpeed;
[SerializeField] private float m_RunSpeed;
[SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
[SerializeField] private float m_JumpSpeed;
[SerializeField] private float m_StickToGroundForce;
[SerializeField] private float m_GravityMultiplier;
[SerializeField] private MouseLook m_MouseLook;
[SerializeField] private bool m_UseFovKick;
[SerializeField] private FOVKick m_FovKick = new FOVKick();
[SerializeField] private bool m_UseHeadBob;
[SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
[SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
[SerializeField] private float m_StepInterval;
[SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from.
[SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground.
[SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground.
private Camera m_Camera;
private bool m_Jump;
private float m_YRotation;
private Vector2 m_Input;
private Vector3 m_MoveDir = Vector3.zero;
private CharacterController m_CharacterController;
private CollisionFlags m_CollisionFlags;
private bool m_PreviouslyGrounded;
private Vector3 m_OriginalCameraPosition;
private float m_StepCycle;
private float m_NextStep;
private bool m_Jumping;
private AudioSource m_AudioSource;
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Camera = Camera.main;
m_OriginalCameraPosition = m_Camera.transform.localPosition;
m_FovKick.Setup(m_Camera);
m_HeadBob.Setup(m_Camera, m_StepInterval);
m_StepCycle = 0f;
m_NextStep = m_StepCycle/2f;
m_Jumping = false;
m_AudioSource = GetComponent<AudioSource>();
m_MouseLook.Init(transform , m_Camera.transform);
m_WalkSpeed = 5;
}
// Update is called once per frame
private void Update()
{
if(Input.GetKey(KeyCode.LeftShift))
{
m_WalkSpeed = 2;
m_RunSpeed = 2;
}
else
{
m_WalkSpeed = 5;
m_RunSpeed = 10;
}
RotateView();
// the jump state needs to read here to make sure it is not missed
if (!m_Jump)
{
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
{
StartCoroutine(m_JumpBob.DoBobCycle());
PlayLandingSound();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
{
m_MoveDir.y = 0f;
}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
private void PlayLandingSound()
{
m_AudioSource.clip = m_LandSound;
m_AudioSource.Play();
m_NextStep = m_StepCycle + .5f;
}
private void FixedUpdate()
{
float speed;
GetInput(out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x;
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore);
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
m_MoveDir.x = desiredMove.x*speed;
m_MoveDir.z = desiredMove.z*speed;
if (m_CharacterController.isGrounded)
{
m_MoveDir.y = -m_StickToGroundForce;
if (m_Jump)
{
m_MoveDir.y = m_JumpSpeed;
PlayJumpSound();
m_Jump = false;
m_Jumping = true;
}
}
else
{
m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
}
m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
ProgressStepCycle(speed);
UpdateCameraPosition(speed);
m_MouseLook.UpdateCursorLock();
}
private void PlayJumpSound()
{
m_AudioSource.clip = m_JumpSound;
m_AudioSource.Play();
}
private void ProgressStepCycle(float speed)
{
if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
{
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
Time.fixedDeltaTime;
}
if (!(m_StepCycle > m_NextStep))
{
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
PlayFootStepAudio();
}
private void PlayFootStepAudio()
{
if (!m_CharacterController.isGrounded)
{
return;
}
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range(1, m_FootstepSounds.Length);
m_AudioSource.clip = m_FootstepSounds[n];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
// move picked sound to index 0 so it's not picked next time
m_FootstepSounds[n] = m_FootstepSounds[0];
m_FootstepSounds[0] = m_AudioSource.clip;
}
private void UpdateCameraPosition(float speed)
{
Vector3 newCameraPosition;
if (!m_UseHeadBob)
{
return;
}
if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
{
m_Camera.transform.localPosition =
m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
(speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
}
else
{
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
}
m_Camera.transform.localPosition = newCameraPosition;
}
private void GetInput(out float speed)
{
// Read input
float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
float vertical = CrossPlatformInputManager.GetAxis("Vertical");
bool waswalking = m_IsWalking;
#if !MOBILE_INPUT
// On standalone builds, walk/run speed is modified by a key press.
// keep track of whether or not the character is walking or running
m_IsWalking = !Input.GetKey(KeyCode.LeftControl);
#endif
// set the desired speed to be walking or running
speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
m_Input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if (m_Input.sqrMagnitude > 1)
{
m_Input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
{
StopAllCoroutines();
StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
}
}
private void RotateView()
{
m_MouseLook.LookRotation (transform, m_Camera.transform);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
//dont move the rigidbody if the character is on top of it
if (m_CollisionFlags == CollisionFlags.Below)
{
return;
}
if (body == null || body.isKinematic)
{
return;
}
body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
}
}
}
KOpp0t:
I know this question gets asked a lot here, but I have been reading for a while and still dont know how to do it…
I am using Unity Standerd Asset FirstPersonController script, and it has a float called “m_RunSpeed”
I hjave made a script called StatusBars that has a variable called “SprintSpeed”.
I want the FirstPersonController script value of “m_RunSpeed” to be equal to “SprintSpeed”.
Here is my StatusBars script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class StatusBars : MonoBehaviour
{
public Slider HealthSlider;
public Slider HungerSlider;
public Slider EnergySlider;
public float HP;
public float Hunger;
public float Energy;
public float WalkDecreaseTime;
public float SprintDecreaseTime;
private float DecreaseTime;
public float EnergyIncreaseTime;
public float EnergyDecreaseTime;
public bool Increasing;
public bool isSprinting;
private float SprintSpeed;
public float DefaultSprintSpeed;
public float DecreasedSprintSpeed;
// Start is called before the first frame update
void Start()
{
HealthSlider.value = HP;
HungerSlider.value = Hunger;
EnergySlider.value = Energy;
DecreaseTime = WalkDecreaseTime;
SprintSpeed = DefaultSprintSpeed;
}
// Update is called once per frame
void Update()
{
if(Input.GetKey(KeyCode.LeftControl))
{
isSprinting = true;
}
else
{
isSprinting = false;
}
if(isSprinting == true)
{
DecreaseTime = SprintDecreaseTime;
SprintSpeed = DefaultSprintSpeed;
}
else
{
DecreaseTime = WalkDecreaseTime;
}
if(Energy >= 0)
{
SprintSpeed = DecreasedSprintSpeed;
}
else
{
SprintSpeed = DefaultSprintSpeed;
}
if(Energy < 100 && isSprinting == false)
{
Energy = Energy += EnergyIncreaseTime * Time.deltaTime;
}
if(Energy > 0 && isSprinting == true)
{
Energy = Energy -= EnergyDecreaseTime * Time.deltaTime;
}
Hunger = Hunger -= DecreaseTime * Time.deltaTime;
Refresh();
}
public void Refresh()
{
HealthSlider.value = HP;
HungerSlider.value = Hunger;
EnergySlider.value = Energy;
}
}
Please assist
Well it’s a private member variable, so you won’t be able to access or change it from any other scripts. You can always just copy Unity’s code into a new script and make that one public though, or better yet, create a setter method for it.
You can apparently access it through reflection, however it’s strongly not recommended.
Referencing variables, fields, methods (anything non-static) in other script instances:
Like all inter-script interaction, all you need is:
Script A needs a reference to script B, which you will populate in the editor:
// inside of ScriptA:
public ScriptB myBScript;
Script B needs to have something public that script A can change:
// variable / field inside of ScriptB:
public int myFooInteger;
// function inside of ScriptB:
public void DoStuff( string reason)
{
}
Script A can then change it directly using the reference to B:
// here is ScriptA accessing something in Scrip…
within a class there are reference to gameobjects in the scene A,
the same gameobjects are available in the scene B.
i have dragged the gameobjects in scene A into inspector fields. now how to reference these gameobjects in the scene B via script into relevant fields in the inspector?
please give me some idea. thanls.
REMEMBER: it isn’t always the best idea for everything to access everything else all over the place. For instance, it is BAD for the player to reach into an enemy and reduce his health.
Instead there should be a function you call on the enemy to reduce his health. All the same rules apply for the above steps: the function must be public AND you need a reference to the class instance.
That way the enemy (and only the enemy) has code to reduce his health and simultaneously do anything else, such as kill him or make him reel from the impact, and all that code is centralized in one place.
KOpp0t
March 6, 2022, 2:38pm
5
RadRedPanda:
Well it’s a private member variable, so you won’t be able to access or change it from any other scripts. You can always just copy Unity’s code into a new script and make that one public though, or better yet, create a setter method for it.
You can apparently access it through reflection, however it’s strongly not recommended.
Thank you for helping!
I never knew that the script was a private member variable. Is there anyway to make it public? or do I need to copy the code and make a new script with the same code in it
KOpp0t
March 6, 2022, 3:01pm
6
nevermind, i have copied and pasted the script into my own one, and it works perfectly!
tysm for the help