I am pretty new to C# and unity,so my question could be basic. However it has bugged me for so long, that I couldn't get it over even after I research it over the internet.
Anyway, here is my question, I have got this error
NullReferenceException: Object reference not set to an instance of an object AchievementButton.click()(at Assets/scripts/AchievementSystem/AchievementButton.cs:25) AchievementManager.Start()(at Assets/scripts/AchievementSystem/AchievementManager.cs:30)
when clicked on play or when click a button to view my list of achievements.
AchievementManager Script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class AchievemenetManager : MonoBehaviour
{
public GameObject achievementPrefab;
public Sprite[] sprites;
public AchievementButton activeButton;
public ScrollRect scrollRect;
// Use this for initialization
void Start ()
{
//here is where the error is logged from
activeButton = GameObject.Find("Streakbtn").GetComponent<AchievementButton>();
CreateAchievement("Streak","testTitle","this is a description",3,0);
activeButton.click();
}
// Update is called once per frame
void Update () {
}
public void CreateAchievement(string category,string title,string description,int points, int spriteIndex)
{
GameObject achievement = (GameObject)Instantiate(achievementPrefab);
SetAchievementInfo(category, achievement,title,description,points,spriteIndex);
}
public void SetAchievementInfo(string category, GameObject achievement, string title, string description, int points, int spriteIndex)
{
achievement.transform.SetParent(GameObject.Find(category).transform);
achievement.transform.localScale = new Vector3(1, 1, 1);
achievement.transform.localPosition = new Vector3(0, 0, 0);
achievement.transform.GetChild(0).GetComponent<Text>().text = title;
achievement.transform.GetChild(1).GetComponent<Text>().text = description;
achievement.transform.GetChild(2).GetComponent<Text>().text = points.ToString();
achievement.transform.GetChild(3).GetComponent<Image>().sprite = sprites[spriteIndex];
}
public void ChangeCategery(GameObject button)
{
AchievementButton achievementButton = button.GetComponent<AchievementButton>();
scrollRect.content = achievementButton.achievementList.GetComponent<RectTransform>();
achievementButton.click();
activeButton.click();
activeButton = achievementButton;
}
}
AchievementButton Script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class AchievementButton : MonoBehaviour
{
public GameObject achievementList;
public Sprite neutral, highlight;
private Image sprite;
void awake()
{
sprite = GetComponent<Image>();
}
public void click()
{
//here is where the error is logged from
if(sprite.sprite == neutral)
{
sprite.sprite = highlight;
achievementList.SetActive(true);
}
else
{
sprite.sprite = neutral;
achievementList.SetActive(false);
}
}
}