I am trying to make a 2D game. My approach, in terms of animation, is to simply change the materials as runtime. I figured a lot of my objects are going to need to animate so I made an ImageAnimation class which will take care of the initialization and the PlayAnimation.
I am new to Object oriented programming and I think I am getting hung up in my logic somewhere. I have attached below the two scripts,
I am receiving the error on the ImageAnimation script on line 32 "Object reference not set to an instance of an object.
Thank you very much for you help in advance.
ImageAnimation.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ImageAnimation : MonoBehaviour
{
public string fileName; //The filename of the animation sequence in the Resource folder.
public bool loop; // Will make the animation repeat if true
public float pictureRateInSeconds; //How long in between the frames
public List<Texture2D> imagePictures; //Will hold all the images
public int imageCounter; //Will be the index variable when going through the imags
public float nextPic = 0f; // Holds the current time and will be checked to see if the next frame should begin
void Awake()
{
imagePictures = new List<Texture2D>(); //Initilize the List
imageCounter = 1;
pictureRateInSeconds = 0.04166666666666666666f;
}
public void InitializeImage(string fileName)
{
imageTextures = Resources.LoadAll( fileName, typeof(Texture2D)); //Loads all the images in the resource folder.
for(var i = 0; i < imageTextures.Length; i++)
{
imagePictures.Add((Texture2D)imageTextures*); // Eror Line //Cycles through each image and adds them to the imagePictures*
-
}* -
}*
-
public void PlayAnimation(bool loop)*
-
{*
-
bool toggle = true;* -
if(Time.time > nextPic && toggle)* -
{* -
if(imageCounter >= imagePictures.Count)//if you reach the end of the animation* -
{* -
if(loop) //Reset the image counter* -
{ * -
imageCounter = 1;* -
}* -
else //Toggle off the animation so it wont repeat* -
{ * -
toggle = false;* -
}* -
} * -
if(toggle) // When the animation is still true, change the material* -
{* -
nextPic = Time.time + pictureRateInSeconds;* -
renderer.material.mainTexture = imagePictures[imageCounter];* -
imageCounter += 1;* -
}* -
} * -
}*
}
The Following is the script for:
Player.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Player : MonoBehaviour
{
-
public ImageAnimation jump; // will hold the jump animation*
-
void Start()*
-
{*
-
jump = new ImageAnimation(); //jump variable is initlized to store all the jump images* -
jump.InitializeImage("Jump"); //should begin the animation of "Jump"* -
}*
-
void Update()*
-
{*
-
}*
}