- Home /
Scramble GetPixels function...
I'm trying to realize a trivia games with images.
But I've got a lot of problem with the SetPixels/GetPixels. I wasn't able to get a part of an image.
The basic idea is to create cubes and put images over these with an algorythm (perlin noise, shuffle cubes, many images, overlapped, etc).
The recipe (for now, I need to improve my code!) :
Hierarchy: Empty GameObject Main Camera * Main Light
Project: * Prefab (standard cube from Unity) and these scripts :
DynamicImagesLib class which can load an image (it works if I put the full image on a face of a cube)
using UnityEngine; using System.IO; using System.Collections.Generic;
public class DynamicImagesLib //: MonoBehaviour { private Dictionary<int, string> imgDict = new Dictionary<int, string>();
//Get all the images path from the folder specified
public void FillImagesCatalogue(string MainImagesFolder)
{
imgDict.Clear();
IterateThroughFolder(MainImagesFolder);
}
public int NumOfImages()
{
return imgDict.Count;
}
public string GetRandomImagePath(bool RemoveAfter)
{
if (imgDict.Count == 0)
{
return string.Empty;
}
//Thread.Sleep(Random.Range(1, 50));
int iIndex = Random.Range(1, imgDict.Count);
string sImg = imgDict[iIndex];
//Console.WriteLine("RANDOM - " + iIndex.ToString() + "-" + sImg + "-" + "COUNT=" + imgDict.Count);
if (RemoveAfter)
{
imgDict.Remove(iIndex);
//Console.WriteLine("REMOVED - " + "COUNT=" + imgDict.Count);
//Replace the key removed with the last element of the dictionnary
if (iIndex <= imgDict.Count)
{
imgDict.Add(iIndex, imgDict[imgDict.Count + 1]);
//Console.WriteLine("ADDED - " + "COUNT=" + imgDict.Count);
imgDict.Remove(imgDict.Count);
//Console.WriteLine("REMOVED - " + "COUNT=" + imgDict.Count);
}
//Console.WriteLine("=========================");
}
return sImg;
}
private void IterateThroughFolder(string currentFolder)
{
string[] allFiles = Directory.GetFiles(currentFolder);
foreach (string sFile in allFiles)
{
if (sFile.EndsWith(".jpg") || sFile.EndsWith(".jpeg") ||
sFile.EndsWith(".bmp") || sFile.EndsWith(".gif")
)
{
imgDict.Add(imgDict.Count + 1, sFile);
}
}
string[] allFolders = Directory.GetDirectories(currentFolder);
foreach (string subFolder in allFolders)
{
IterateThroughFolder(subFolder);
}
}
public byte[] LoadImageIntoByteArray(string sImgPath)
{
byte[] bytImgData = null;
using (FileStream fs = new FileStream(sImgPath, FileMode.Open, FileAccess.Read))
{
int iImgSize = (int)fs.Length;
bytImgData = new byte[iImgSize];
fs.Read(bytImgData, 0, iImgSize);
fs.Close();
}
return bytImgData;
}
}
I also attached this script to the Empty Game object :
using System.Collections.Generic; using UnityEngine;
public class ScriptBoardCreation : MonoBehaviour { #region Variables private Dictionary<string, MyTile> _ht = new Dictionary<string, MyTile>(); private DynamicImagesLib img = new DynamicImagesLib(); #endregion Variables
#region Proprits publiques
public string ImagesFolder;
public int NumOfTilesWidth;
public int NumOfTilesHeight;
public GameObject tile;
public MonoBehaviour strategy;
#endregion Proprits publiques
#region Mthodes prdfinies de Unity
public void Start ()
{
CreateBoard();
PrepareImages();
}
public void FixedUpdate()
{
((IGameStrategy)strategy).Render(_ht);
}
#endregion Mthodes prdfinies de Unity
#region Mthodes
public void CreateBoard()
{
//Cration des tuiles en forme de cubes
for (int x = 0; x < NumOfTilesWidth; x++)
{
for (int y = 0; y < NumOfTilesHeight; y++)
{
MyTile t = new MyTile(tile, x, y, transform);
_ht.Add(t.Name, t);
}
}
//Repositionnement de la camra et de la lumire...
GameObject.Find("Main Camera").transform.position = new Vector3(NumOfTilesWidth / 2, NumOfTilesHeight / 2, -5);
GameObject.Find("Main Light").transform.position = new Vector3(NumOfTilesWidth / 2, NumOfTilesHeight / 2, -10);
//Stratgie pour le jeu
this.RefreshFaces();
}
public void RefreshFaces()
{
((IGameStrategy)strategy).Run(_ht);
}
public void PrepareImages()
{
img.FillImagesCatalogue(ImagesFolder);
}
#endregion Mthodes
}
To work properly the previous script need a strategy. So, I attached the script to the Empty Game Object and I drag and drop a script who inherits from : IGameStrategy
using UnityEngine; using System.Collections.Generic;
//Interface pour les stratgies de jeu qui peuvent tre substitu l'une l'autre. public interface IGameStrategy { void Run(Dictionary<string, MyTile>Board);
void Render(Dictionary<string, MyTile>Board);
}
and this other file :
using UnityEngine; using System.Collections.Generic;
public class GameStrategyLoadImg : MonoBehaviour, IGameStrategy {
public void Run(Dictionary<string, MyTile> Board) {
DynamicImagesLib img = new DynamicImagesLib(); img.FillImagesCatalogue(@"C:\Users\Martin\Pictures\Sample Pictures");
string sImgPath = img.GetRandomImagePath(true);
byte[] b = img.LoadImageIntoByteArray(sImgPath);
Texture2D tex2D = new Texture2D(1024, 768);
tex2D.LoadImage(b);
/*
foreach (MyTile tile in Board.Values)
{
tile.UnityGameObject.renderer.materials[0] = null;
tile.UnityGameObject.renderer.material.mainTexture = tex2D;
}
*/
int NumOfTilesHeight = 9;
int NumOfTilesWidth = 16;
int iH = tex2D.height / NumOfTilesHeight;
int iW = tex2D.width / NumOfTilesWidth;
Color[] col = null;
Texture2D txt = null;
foreach (MyTile tile in Board.Values)
{
//col = tex2D.GetPixels(tile.x * iW, tile.y * (NumOfTilesHeight - iH), iW, iH, 0);
col = tex2D.GetPixels(tile.x * iW, tile.y * iH, iW, iH); //, 0);
txt = new Texture2D(iH, iW); //, TextureFormat.RGB24, false);
txt.SetPixels(col); //, 0);
tile.UnityGameObject.renderer.material.mainTexture = txt;
}
}
public void Render(Dictionary<string, MyTile>Board)
{
}
}
You will also need this class (wrapper for a tile for the creation of the board :
using UnityEngine; using System.Collections;
//Tuile pour le jeu public class MyTile { private int _x = 0; private int _y = 0; private GameObject _go = null; private string _sName = string.Empty;
public MyTile(GameObject goTemplate, int iX, int iY, Transform myParent)
{
_x = iX;
_y = iY;
_sName = _x + "_"+ _y;
float posX = x;
float posY = y;
_go = (GameObject)Object.Instantiate(goTemplate, new Vector3(posX, posY, 0.0f), new Quaternion(0, 90, 0, 0));
_go.name = _sName;
_go.transform.parent = myParent;
}
//Position de la tuile en X. Proprit en lecture seule.
public int x
{
get
{
return _x;
}
}
//Position en Y. Proprit en lecture seule.
public int y
{
get
{
return _y;
}
}
//Nom de l'objet. Proprit en lecture seule.
public string Name
{
get
{
return _sName;
}
}
//Objet 3D dans Unity. Proprit en lecture seule.
public GameObject UnityGameObject
{
get
{
return _go;
}
}
}
If someone could help be, it will be greatly appreciated...
Btw, I love using strategy design pattern in Unity, it is very easy to experiment!
Thanks in advance,
Martin
Your answer
Follow this Question
Related Questions
Resetting a Material's Texture After GetPixels/SetPixels 1 Answer
Merging Textures At Runtime - Not Correct? 1 Answer
Changing color of Texture2d with transparency 1 Answer
Painting stencil on a surface. 6 Answers
Setting pixels on a texture? 2 Answers