Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

help coding for slider ui for player attributes

Discussion in 'Scripting' started by hamzah2412, May 12, 2020.

  1. hamzah2412

    hamzah2412

    Joined:
    Jul 8, 2019
    Posts:
    9
    Im getting a nullreference for this code below which suppose to reference from the playercontroller, can someone check it this out tnks.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class DiseaseProgression : MonoBehaviour
    7. {
    8.     [Header("Disease Progression Bar")]
    9.     public Slider slider;
    10.     float timeToWait = 1f;
    11.     float fillQuantity = 2f;
    12.  
    13.  
    14.     [Header("Reference")]
    15.     private PlayerController1 m_Player1;
    16.     private PlayerController2 m_Player2;
    17.  
    18.     // Start is called before the first frame update
    19.     void Start()
    20.     {
    21.         StartCoroutine(FillSlider());
    22.  
    23.         m_Player1 = GetComponent<PlayerController1>();
    24.  
    25.     }
    26.  
    27.     public IEnumerator FillSlider()
    28.     {
    29.         yield return new WaitForSeconds(timeToWait);
    30.         slider.value += fillQuantity;
    31.         StartCoroutine(FillSlider());
    32.     }
    33.  
    34.     public void OnValueChanged(int speedReduction40 = 15)
    35.     {
    36.        
    37.         if (slider.value >= 40)
    38.         {
    39.             m_Player1.moveSpeed = (speedReduction40 / 100) * m_Player1.moveSpeed;        
    40.         }
    41.         else
    42.         {
    43.             FillSlider();
    44.         }
    45.      
    46.        
    47.     }
    48.  
    49. }
    Code (CSharp):
    1. public class PlayerController1 : MonoBehaviour
    2. {
    3.  
    4.     [Header("References")]
    5.     private Rigidbody2D rb; //Store a reference to the Rigidbody2D component required to use 2D physics
    6.     public Animator myAnim;  //Store a reference to the Animator component. Needs to be accessible for AttackController
    7.     private LevelManager theLevelManager;
    8.     private EnemyAIController theEnemy; //Make a reference to an object of EnemyController *To be unchecked*
    9.     AttackController1 m_Attack;
    10.     SpriteRenderer m_sr;
    11.     public PlayerController1 m_Player1;
    12.     private PlayerController2 m_Player2;
    13.  
    14.  
    15.     [Header("Respawn Position")]
    16.     //Store a respawn position the player will go to whenever she dies.
    17.     public Vector3 respawnPosition;
    18.  
    19.     [Header("Movement")]
    20.     //Control speed of player that is moving
    21.     public float moveSpeed;
    22.     public bool canMove = true;
    23.  
    24.     [Header("Jump")]
    25.     //Jump Variables
    26.     public float jumpSpeed; //Control the speed when player jumps
    27.     public float jumpForce; //Control the strength and added force of jump
    28.     private bool doubleJump; //Control the jump when he player jump double times or click spacebar double times
    29.  
    30.     private float jumpPressedRemember;
    31.     public float jumpPressedRememberTime;
    32.  
    33.     private float GroundedRemember;
    34.     public float GroundedRememberTime;
    35.  
    36.     //Enable or Disables double jump feature
    37.     public bool canDoubleJump;
    38.  
    39.     [Header("Ground Variables")]
    40.     //Ground detection variables
    41.     public Transform groundCheck; //A point is space to check where the ground is
    42.     public float groundCheckRadius;
    43.     public LayerMask realGround;
    44.     public bool isGrounded;
    45.  
    46.     [Header("Knockback")]
    47.     //Knockback Variables
    48.     public float knockbackForce; //Knockback strength
    49.     public float knockbackDuration; //Duration in seconds of every knockback
    50.     private float currentKnockbackDuration; // Remaining duration of existing knockback
    51.  
    52.     [Header("Better Jump")]
    53.     //Jump Modifications
    54.     public float highJumpMultiplier = 2.5f;
    55.     public float lowJumpMultiplier = 2f;
    56.  
    57.     [Header("Melee Attack System")]
    58.     //Attack System
    59.     public float PlayerDamage = 100;
    60.  
    61.     private float timeBetweenAttacks;
    62.     [HideInInspector] public float startTimeBetweenAttacks;
    63.     public float defaultTimeBetweenAttacks;
    64.     public float TimeBetweenAttacksMultiplier;
    65.  
    66.     public Transform AttackPos;
    67.     public LayerMask WhoIsEnemy;
    68.  
    69.     [Header("Invunerable effect")]
    70.     public float blinkTime;
    71.  
    72.     [HideInInspector] public float CurrentPlayerDamage;
    73.  
    74.     [Header("Key System")]
    75.     private List<Key.KeyType> keyList;
    76.  
    77.     //Tag System
    78.     [HideInInspector] public bool activePlayer;
    79.  
    80.  
    81.  
    82.  
    83.     // Start is called before the first frame update
    84.     void Start()
    85.     {
    86.         //Get and store a reference to the Rigidbody2D component so that we can access it.
    87.         rb = GetComponent<Rigidbody2D>();
    88.         //Access animator component.
    89.         myAnim = GetComponent<Animator>();
    90.         respawnPosition = transform.position; //When game starts, respawn position equals to the current players position.
    91.         m_sr = GetComponent<SpriteRenderer>();
    92.         theLevelManager = FindObjectOfType<LevelManager>();
    93.         m_Attack = GetComponentInChildren<AttackController1>();
    94.         m_Player1 = GetComponent<PlayerController1>();
    95.         m_Player2 = GetComponent<PlayerController2>();
    96.    
    97.  
    98.         startTimeBetweenAttacks = defaultTimeBetweenAttacks;
    99.         CurrentPlayerDamage = PlayerDamage;
    100.         Debug.Log(CurrentPlayerDamage);
    101.  
    102.     }
    103.  
    104.     // Update is called once per frame
    105.     void Update()
    106.     {
    107.         if (!canMove)
    108.         {
    109.  
    110.             //Mathf.Abs function returns the absolute value of velocity rigidbody along 'x' axis.
    111.             myAnim.SetFloat("Speed", Mathf.Abs(rb.velocity.x));
    112.  
    113.             //SetBool is used to trigger transitions between Animator states.
    114.             myAnim.SetBool("Ground", isGrounded);
    115.             return;
    116.         }
    117.  
    118.         if (currentKnockbackDuration <= 0) // If we are currently being knocked back, this will disable all player controls
    119.         {
    120.             //Player Blinking
    121.             if (blinkTime > 0)
    122.             {
    123.                 m_sr.color = new Color32(200, 200, 200, 230);
    124.                 blinkTime -= Time.deltaTime;
    125.             }
    126.             else
    127.             {
    128.                 m_sr.color = new Color32(255, 255, 255, 255);
    129.             }
    130.  
    131.             //Attack Animation, set exit time on animator that links to Player_Attack so it does not jerk.
    132.  
    133.             if (timeBetweenAttacks <= 0)
    134.             {
    135.                 if (Input.GetKeyDown(KeyCode.L))
    136.                 {
    137.  
    138.                     m_Attack.attack();
    139.                     Debug.Log("Pressed the L Key.");
    140.                     //Attack Availability
    141.                     timeBetweenAttacks = startTimeBetweenAttacks;
    142.  
    143.                     //theLevelManager.swordSound.Play();
    144.                 }
    145.             }
    146.             else
    147.             {
    148.                 timeBetweenAttacks -= Time.deltaTime;
    149.             }
    150.  
    151.          
    152.  
    153.             float h = Input.GetAxisRaw("Horizontal"); //Movement Variable
    154.            
    155.  
    156.  
    157.             //Movement Controls
    158.             rb.velocity = new Vector2(moveSpeed * h, rb.velocity.y);        
    159.  
    160.  
    161.  
    162.             if (h > 0) //when its more than 0 it will face right
    163.             {            
    164.                     transform.localScale = new Vector3(1, 1, 1);            
    165.             }
    166.             else if (h < 0) //when its less than 0 it will face left
    167.             {            
    168.                     transform.localScale = new Vector3(-1, 1, 1);
    169.             }
    170.  
    171.             rb.velocity = new Vector2(moveSpeed * h, rb.velocity.y);
    172.  
    173.             jumpPressedRemember -= Time.deltaTime;
    174.             GroundedRemember -= Time.deltaTime;
    175.  
    176.             if (isGrounded)
    177.             {
    178.                 GroundedRemember = GroundedRememberTime;
    179.             }
    180.  
    181.             if (Input.GetButtonDown("Jump"))
    182.             {
    183.                 jumpPressedRemember = jumpPressedRememberTime;
    184.             }
    185.  
    186.             //Jump Controls
    187.             if (jumpPressedRemember > 0 && GroundedRemember > 0)
    188.             {
    189.                 jumpPressedRemember = 0;
    190.                 GroundedRemember = 0;
    191.                 //For Jumping
    192.                 rb.velocity = new Vector2(rb.velocity.x, jumpSpeed);
    193.  
    194.                 rb.AddForce(new Vector2(0, jumpForce));
    195.  
    196.                 //Jump if player is grounded from IsGrounded
    197.                 doubleJump = true;
    198.  
    199.                 //Play dust effect when jumping
    200.                 //CreateDust();
    201.  
    202.                 rb.velocity = Vector2.up * jumpForce;
    203.             }
    204.             else if (doubleJump == true && Input.GetButtonDown("Jump"))
    205.             {
    206.                 if (!canDoubleJump) return;
    207.                 //Condition to prevent infinite jumping
    208.  
    209.                 rb.AddForce(new Vector2(5, jumpForce));
    210.  
    211.                 //Does not make player jump again when player is in the air from using player's already double jump and that the jump button is already pressed and used
    212.                 doubleJump = false;
    213.  
    214.                 //Play dust effect when jumping
    215.                 //CreateDust();
    216.  
    217.                 rb.velocity = Vector2.up * jumpForce;
    218.             }
    219.  
    220.             //To create circle and checking collision.
    221.             isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, realGround);
    222.  
    223.             //Mathf.Abs function returns the absolute value of velocity rigidbody along 'x' axis.
    224.             myAnim.SetFloat("Speed", Mathf.Abs(rb.velocity.x));
    225.  
    226.             //SetBool is used to trigger transitions between Animator states.
    227.             myAnim.SetBool("Ground", isGrounded);
    228.  
    229.         }
    230.         else
    231.         {
    232.             //Handle the situation we are currently being knocked back.
    233.             currentKnockbackDuration -= Time.deltaTime;
    234.  
    235.             //Force the knockback of the player
    236.             if (transform.localScale.x > 0)
    237.             {
    238.                 rb.velocity = new Vector3(-knockbackForce, knockbackForce * .5f, 0.0f);
    239.             }
    240.             else
    241.             {
    242.                 rb.velocity = new Vector3(knockbackForce, knockbackForce * .5f, 0.0f);
    243.             }
    244.         }
    245.  
    246.      
    247.  
    248.     }//End Of Void Update
    249.  
    250.     public void Knockback()
    251.     {
    252.         currentKnockbackDuration = knockbackDuration;
    253.     }
    254.  
    255.     void FixedUpdate()
    256.     {
    257.         //Jump Modifications
    258.         if (rb.velocity.y < 0)
    259.         {
    260.             rb.velocity += Vector2.up * Physics2D.gravity.y * (highJumpMultiplier - 1) * Time.deltaTime;
    261.         }
    262.         else if (rb.velocity.y > 0 && !Input.GetButton("Jump"))
    263.         {
    264.             rb.velocity += Vector2.up * Physics2D.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
    265.         }
    266.     }//End Of FixedUpdate.
    267.  
    268.     //Variable to trigger player respawn & key colliding.
    269.     void OnTriggerEnter2D(Collider2D other)
    270.     {
    271.         if (other.tag == "KillPlane")
    272.         {
    273.             theLevelManager.Respawn();
    274.         }
    275.  
    276.         Key key = other.GetComponent<Key>();
    277.  
    278.         if (key != null)
    279.         {
    280.             AddKey(key.GetKeyType());
    281.             Destroy(key.gameObject);
    282.         }
    283.  
    284.         KeyDoor keyDoor = other.GetComponent<KeyDoor>();
    285.         if(keyDoor != null)
    286.         {
    287.             if(ContainsKey(keyDoor.GetKeyType()))
    288.             {
    289.                 //Currently holding Key to open this door
    290.                 RemoveKey(keyDoor.GetKeyType());
    291.                 keyDoor.OpenDoor();
    292.             }
    293.         }
    294.  
    295.     }
    296.  
    297.     //To play dust effect when jumping.
    298.     void CreateDust()
    299.     {
    300.         //dust.Play();
    301.     }
    302.  
    303.     public bool isFalling()
    304.     {
    305.         if (rb.velocity.y < 0) return true;
    306.         return false;
    307.     }
    308.  
    309.     public void takeHit(int damage)
    310.     {
    311.        
    312.         theLevelManager.HurtPlayer(damage, true);
    313.     }
    314.  
    315.     //CollisionEnter for player entering MovingPlatform.
    316.     void OnCollisionEnter2D(Collision2D collision)
    317.     {
    318.         if (collision.gameObject.tag == "MovingPlatform")
    319.         {
    320.             gameObject.transform.parent = collision.transform;        
    321.         }
    322.  
    323.  
    324.     }
    325.  
    326.     //CollisionExit for player exiting MovingPlatform.
    327.     void OnCollisionExit2D(Collision2D collision)
    328.     {
    329.         if (collision.gameObject.tag == "MovingPlatform")
    330.         {          
    331.             gameObject.transform.parent = null;              
    332.         }
    333.  
    334.     }
    335.  
    336.     private void Awake()
    337.     {
    338.         keyList = new List<Key.KeyType>();
    339.     }//End Of Awake.
    340.  
    341.     public void AddKey(Key.KeyType keyType)
    342.     {
    343.         Debug.Log("Added Key: " + keyType);
    344.         keyList.Add(keyType);
    345.     }
    346.  
    347.     public void RemoveKey(Key.KeyType keyType)
    348.     {
    349.         keyList.Remove(keyType);
    350.     }
    351.  
    352.     public bool ContainsKey(Key.KeyType keyType)
    353.     {
    354.         return keyList.Contains(keyType);
    355.     }
    356.  
    357.  
    358. }
     
  2. hamzah2412

    hamzah2412

    Joined:
    Jul 8, 2019
    Posts:
    9
    Under the Onvaluechanged which supposed to affect the movespeed tnks.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    I'm developing a new response to this most-common question:

    http://plbm.com/?p=221

    Feedback and comments to that post are always welcome.
     
  4. hamzah2412

    hamzah2412

    Joined:
    Jul 8, 2019
    Posts:
    9
    actually its more of the slider value not affecting the player stats, any hints? like the parameters to code a bar to affect player movespeed/ attackspeed etc. tnks
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    1. fix the nullref; if you don't fix the nullref, all the hints in the world won't help you. IF you fixed the nullref, then:

    2. start inserting Debug.Log() statements to see what values are coming from where, and to determine if you're even calling the code you think you are... this is Debugging 101.