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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Script error, help

Discussion in 'Scripting' started by Paykoman, Nov 30, 2016.

  1. Paykoman

    Paykoman

    Joined:
    Jun 26, 2014
    Posts:
    500
    Hi guys, im having a little error in my script and i cant figure it out what am i doing wrong.. could someone help me plz? appreciate



    Code (CSharp):
    1. ing UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5. public class CharacterStats : MonoBehaviour
    6. {
    7.     public List<BaseStats> stats = new List<BaseStats>();
    8.  
    9.     void Start()
    10.     {
    11.         stats.Add (new BaseStats(4, "Strenght", "Your attack power."));
    12.         stats.Add (new BaseStats(2, "Vitality", "Your vitality level."));
    13.     }
    14.  
    15.     public void AddStatBonus(List<BaseStats> statBonuses)
    16.     {
    17.         foreach(BaseStats statBonus in statBonuses)
    18.         {
    19.             stats.Find (x => x.StatName == statBonus.StatName).AddStatBonus (new StatsBonus (statBonus.BaseValue));
    20.         }
    21.     }
    22.  
    23.     public void RemoveStatBonus(List<BaseStats> statBonuses)
    24.     {
    25.         foreach(BaseStats statBonus in statBonuses)
    26.         {
    27.             stats.Find (x=> x.StatName == statBonus.StatName).RemoveStatBonus(new StatsBonus(statBonus.BaseValue));
    28.         }
    29.     }
    30. }
     
  2. magnite

    magnite

    Joined:
    Dec 12, 2012
    Posts:
    125
    Your issue is in the function AddStatBonus at this line:


    Code (csharp):
    1. stats.Find (x => x.StatName == statBonus.StatName).AddStatBonus (new StatsBonus (statBonus.BaseValue));
    You have several scenarios:
    1. Your stats list is null
    2. The statBonus variable is null
    3. The returned value from Find is also null

    My suggestion:
    Split this up into more than one line and add some checks to make sure you are not operating on null values.