﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TextureUpdateBehavior : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        _texture = new Texture2D(Cols, Rows, TextureFormat.RGB24, false);

        int numPixels = Cols * Rows * 3;
        _pixels = new byte[numPixels];
        for (int i = 0; i < numPixels; ++i)
        {
            _pixels[i] = 0;
        }

        _texture.LoadRawTextureData(_pixels);
        _texture.Apply();

        GetComponent<Renderer>().material.mainTexture = _texture;
    }

    // Update is called once per frame
    void Update()
    {
        _delta += Time.deltaTime;
        if (_delta > 0.04f)
        {
            _delta = 0.0f;

            Debug.Log("Texture2D native pointer = " + _texture.GetNativeTexturePtr().ToString("X16"));

            int index = r * Cols * 3 + c * 3;
            _pixels[index + 0] = rColor;
            _pixels[index + 1] = gColor;
            _pixels[index + 2] = bColor;

            _texture.LoadRawTextureData(_pixels);
            _texture.Apply();

            c += 1;
            if (c >= Cols)
            {
                c = 0;
                r += 1;
                if (r >= Rows)
                {
                    r = 0;
                    byte color = bColor;
                    bColor = gColor;
                    gColor = rColor;
                    rColor = color;
                }
            }
        }
    }

    const int Rows = 10;
    const int Cols = 10;

    private Texture2D _texture = null;
    private byte[] _pixels = null;
    private float _delta = 0.0f;
    private int r = 0;
    private int c = 0;
    private byte rColor = 255;
    private byte gColor = 0;
    private byte bColor = 0;
}
