Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Martin Dor · Apr 20, 2011 at 02:53 AM · texture2dsetpixelsgetpixels

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 &lt;= 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 &lt; NumOfTilesWidth; x++)
     {
         for (int y = 0; y &lt; 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&lt;string, MyTile&gt;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&lt;string, MyTile&gt;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

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
3

Answer by Bunny83 · Apr 20, 2011 at 03:37 AM

Nice, i like to see more people using design patterns.
The only thing i can see is that you don't use Apply() after changing the image. I think that's your problem.

Good luck and keep on pluggin'

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image DEtH_MoroZ · Aug 20, 2011 at 02:45 AM 0
Share

pwnge :D that was realy nice answer after this code

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

1 Person is following this question.

avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges