I'm in the process of creating a game and the scripts are getting pretty big. For more clarity I want to work with the custom editor. But I have problems with types like classes, gameobjects and especially arrays.
As you can hopefully see in my picture, it is very easy to make basic types like string and float etc visible. But how does it work with an array ? and especially if the array is still a class or a rigidbody or a gameobject ? I need if possible a good explanation or direct solution. I would be very grateful for your help
enter image description here
Note: If your just looking to beautify/improve your inspector, rather than doing it as an actual project/experience, your better off looking for plugins.
The Custom-Editor API that Unity provides are a bunch of Tools, not a House. You will end up pouring a lot of effort into making your inspector 'look neater'.
If you just want to create a game, use plugins to decorate your inspector.
MyBox is one of the Plugins I use, and recommend.
Now back to the question
I managed to pull it off by using a combination of EditorGUILayout.Foldout and looping through the array size to create multiple EditorGUILayout.IntField.
// True if the user 'opened' up the array on inspector.
private bool countIntsOpened;
public override void OnInspectorGUI() {
var myTarget = (N_USE)target;
myTarget.myTest.name = EditorGUILayout.TextField("see name", myTarget.myTest.name);
myTarget.myTest.countOnly = EditorGUILayout.FloatField("see float", myTarget.myTest.countOnly);
// Create int array field
myTarget.myTest.countInts = IntArrayField("see int[]", ref countIntsOpened, myTarget.myTest.countInts);
}
public int[] IntArrayField(string label, ref bool open, int[] array) {
// Create a foldout
open = EditorGUILayout.Foldout(open, label);
int newSize = array.Length;
// Show values if foldout was opened.
if (open) {
// Int-field to set array size
newSize = EditorGUILayout.IntField("Size", newSize);
newSize = newSize < 0 ? 0 : newSize;
// Creates a spacing between the input for array-size, and the array values.
EditorGUILayout.Space();
// Resize if user input a new array length
if (newSize != array.Length) {
array = ResizeArray(array, newSize);
}
// Make multiple int-fields based on the length given
for (var i = 0; i < newSize; ++i) {
array[i] = EditorGUILayout.IntField($"Value-{i}", array[i]);
}
}
return array;
}
private static T[] ResizeArray<T>(T[] array, int size) {
T[] newArray = new T[size];
for (var i = 0; i < size; i++) {
if (i < array.Length) {
newArray[i] = array[i];
}
}
return newArray;
}
Not as nice or neat as Unity's default. But gets the job done.
P.S: You can copy-paste your code when asking questions, rather than posting it as an image. It helps a lot.
Related
When I change material in runtime with this it does not work
expoSceneLarge.GetComponent<Renderer>().materials[0] = availableMaterials[selectedMaterialIndex];
however using this
expoSceneLarge.GetComponent<Renderer>().material = availableMaterials[selectedMaterialIndex];
material is being changed in run time.
What confuses me is that material, according to Unity return the first element in materials attached to renderer, so why materials[0] does not work?
Found a solution.
I has to create new array of materials, change the once I was interested in and the assign whole array to mesh renderer. Here is a a full code for future reference.
var newMaterials = new Material[_expoMaterials.Count()];
for(int i = 0; i < newMaterials.Count(); i++)
{
// i = 1 for floor
if(i == 1)
{
newMaterials[i] = availableMaterials[selectedMaterialIndex];
}
else
{
newMaterials[i] = _expoMaterials[i];
}
}
expoSceneLarge.GetComponent<MeshRenderer>().materials = newMaterials;
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
trying to make a game, i need to make a spawner spawns objects in four colors randomly when we click Fire1 button, in limit number for example 4 times red for time blue.. Etc but randomly and the spawner shows the coming color or the next color, i tried many things but didn't work for me. Any help plz.
I can give you an idea of how to complete it -
First things first I'd say create the 4 game objects you'd like to use in your game in your editor, and assign the appropriate 4 colours in the objects material that you'd like to use.
Create a new folder in your assets called 'Resources' Then Create a Prefab for these objects by dragging them from your project hierarchy into your Resources folder.
Now Create a new empty gameobject and a new C# script in your assets folder, and drag the C# script onto the new empty game object. Inside the C# Script you want a few methods, the following should do the trick given that the prefabs are called shape1, shape2 etc.
//shapes to be spawned
public List<GameObject> shapes;
//shapes that are in game
public List<GameObject> spawnedShape;
//num of next shape to be places
public int next;
//list of shapes that can be spawned
public List<int> shapeCount;
System.Random random;
void Start()
{
random = new System.Random();
for (int i = 0; i < 4; i++)
{
//adds shapes that can be added into shapecount list.
for(int j = 0; j < 4; j++)
{
shapeCount.Add(i);
}
//load game objects from resources into list
GameObject go = Resources.Load("shape" + i) as GameObject;
shapes.Add(go);
}
//set next shape
int next = setNext();
}
void Update()
{
if (Input.GetButton("Fire1")) {
spawnShape();
}
}
public int setNext()
{
if (shapeCount.Count != 0)
{
int num = random.Next(0, shapeCount.Count);
return shapeCount[num];
}
else return -1;
}
void spawnShape()
{
if(next == -1)
{
Debug.Log("Out of shapes");
}else
{
//creates instance of shape
GameObject go = Instantiate(shapes[next]);
//creates and assigns random x, y coordinate
int x = random.Next(0, 500);
int y = random.Next(0, 500);
go.transform.position = new Vector3(x, y, 0);
spawnedShape.Add(go);
}
//gets colour of next shape
next = setNext();
}
Just adjust the code to fit your project, there are more efficient ways of doing it for instance having one shape and adding different materials however this way can allow for all different shapes.
The exercise is as follows:
Rewrite programming exercise 3 from lecture 6 by
creating a class called Button to replace the arrays.
a) Create the class and define class variables that
hold information about position, dimensions and
color. In addition a class variable should be made,
which contains the title of the particular button.
Use the constructor to set the initial values of the
class variables.
So basically, I have to convert a previous exercise I have done into a class.
This is how I made the previous exercise in case you need it: http://pastebin.com/RqM6hj6K
So I tried to convert it into class, but apparently it gives me an error and I cannot see how to fix it.
My teached also said that I don't have to keep it as an array, and could instead make many variables instead of the data in the array.
The language is processing and gives error code NullPointerException
class Button
{
int[] nums;
Button(int n1, int n2, int n3, int n4)
{
nums[0] = n1;
nums[1] = n2;
nums[2] = n3;
nums[3] = n4;
}
void display()
{
fill(255, 0, 0);
rect(nums[0], nums[1], nums[2], nums[3]);
}
};
void setup()
{
size(800, 800);
Button butt = new Button(75, 250, 200, 200);
butt.display();
}
You're only declared nums, but not initialized it.
This results in a NullPointerException: in the constructor you're accessing nums[0], but nums doesn't have a length yet. Try this:
class Button
{
//remember to initialize/allocate the array
int[] nums = new int[4];
Button(int n1, int n2, int n3, int n4)
{
nums[0] = n1;
nums[1] = n2;
nums[2] = n3;
nums[3] = n4;
}
void display()
{
fill(255, 0, 0);
rect(nums[0], nums[1], nums[2], nums[3]);
}
};
void setup()
{
size(800, 800);
Button butt = new Button(75, 250, 200, 200);
butt.display();
}
In the future, always make sure the variables you try to access properties of(arrays/objects) are initialized/allocated first(otherwise you'll get the NullPointerException again and it's no fun)
As #v.k. so nicely points out, it's better to have readable code and remove some of the redundancy.
Before the x,y,width and height of your button were stored in an array. That is all the array could do: store data and that's it! Your class however can not only store the same data as individual easy to read properties, but can also do more: functions! (e.g. display())
So, the more readable version:
class Button
{
//remember to initialize/allocate the array
int x,y,width,height;
Button(int x,int y,int width,int height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
void display()
{
fill(255, 0, 0);
rect(x,y,width,height);//why don't we use this.here or everywhere ?
}
};
void setup()
{
size(800, 800);
Button butt = new Button(75, 250, 200, 200);
butt.display();
}
Yeah, it's sorta easier to read, but what's the deal with this you may ask ?
Well, it's a keyword that allows you to gain access to the object's instance (which ever that may be in the future when you choose to instantiate) and therefore it's properties (classes version of variables) and methods (classes version of functions). There's quite a lot of neat things to learn in terms of OOP in Java, but you can take one step at a time with a nice and visual approach in Processing.
If you haven't already, check out Daniel Shiffman's Objects tutorial
Best of luck learning OOP in Processing!
Flash AS3:
I just need to know how to check a condition for roll over effect on similar colour movieclips which is near by in a group of random colours movieclips in a grid whereas it is using 2D Array in flash AS3.or
I just need roll over event which i wrote is onBoxOver event function, in that the object which i am targetting is only getting rollover or getting alpha changes. But i need to know how to make rollover for similar colour which are all nearby.
The code which i wrote is below for your reference.
Flash AS3::
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class playGame extends MovieClip
{
public static var totalRowBoxes:Number = 13;
public static var totalColumnBoxes:Number = 12;
public static var rowGap:Number = 30;
public static var columnGap:Number = 30;
public static var totalColorBoxes:Number = 8;
public static var boxCollection:Array = new Array();
public static var boxCollection1:Array = new Array();
public function playGame(theGame:main)
{
// constructor code
addBoxOnStage();
}
private function addBoxOnStage():void
{
var borderCont:Banner = new Banner();
var scoreclipCont:scoreclip = new scoreclip();
addChild(borderCont);
addChild(scoreclipCont);
scoreclipCont.x = 0;
scoreclipCont.y = 0;
createLevel(1);
for (var i:Number = 0; i<totalRowBoxes; i++)
{
boxCollection[i] = new Array(i);
for (var j:Number = 0; j<totalColumnBoxes; j++)
{
var squareCont:square = new square();
squareCont.x = 30 + (i * rowGap);
squareCont.y = 30 + (j * columnGap);
squareCont.name = i + "_" + j;
var boxCollection1:Array = new Array();
boxCollection1[0] = Math.round(Math.random() * 8);
boxCollection1[1] = squareCont;
var boxColour:Number = new Number();
boxColour = boxCollection1[0];
boxCollection[i][j] = boxCollection1[1];
addChild(squareCont);
squareCont.gotoAndStop(boxCollection1[0]);
squareCont.addEventListener(MouseEvent.MOUSE_OVER, onBoxOver); squareCont.addEventListener(MouseEvent.MOUSE_OUT, onBoxOut);
squareCont.addEventListener(MouseEvent.CLICK, onBoxClick);
}
}
}
private function onBoxClick(eve:MouseEvent):void
{
}
private function onBoxOver(eve:MouseEvent):void
{
for (var i:Number=0; i< totalRowBoxes; i++)
{
for (var j:Number=0; j<totalColumnBoxes; j++)
{
eve.target.alpha = 0.3;
// trace(boxCollection[i][j].currentFrame)
trace(eve.target);
}
}
}
private function onBoxOut(eve:MouseEvent):void
{
eve.target.alpha = 1;
}
private function createLevel(lvl):void
{
}
}
}
![My Game screenshot here colourbox][1]
Thanks in Advance. Greatly Appreciable for the reply.
Hi this is the image or screenshot of my project. In that image there are 8 colours randomly arranged. whenever i make mouse position or rollover on any box , the condition should check whether the same colour occurs around the box(eg.top, down, left, right) which i am making rollover.
1.If the same colour occur on the top of the box which i am pointing the cursor , the top box and the box which i am pointing both should get less alpha, else only the pointing box should get less alpha. this is my concept friends. please go through the image and let me know if u have any doubts.
I am still unsure what you mean by 'nearby'. (neighbour tiles? adjacent of similar colour?...)
If 'nearby' means adjacent, you need to read about flood fill algorithms. There is a good wiki article about this. You would use that to crawl through the list of tiles similar enough to trigger the effect you want.
I also don't know what 'similar' colour means in your project. You will need a method to determine weather two colours are similar. There is a stackoverflow question re: similar colour detection. It has a good answer to start you out in your research. look here.
I'm a beginner of ActionScript 3.0. I'm making a simple memory game, the tool I'm using is Eclipse with flexsdk plugin. Right now I've done the shuffle and display images, and the cover of the images as well.
My idea is when clicking on the image, the cover will remove and show the image behind of it. After 2 covers are gone, the game will compare and check whether the selected images are match or not, if match both of the images will remain, otherwise the cover will reappear and the game keeps going on. If all of the images are match, a winning line will appear.
The problem I'm facing is I got no idea on how to deal with the images comparison part. I wanted to compare with the index number of array or the name of the images, but I really don't have any idea. I've refer some examples but all of them are develop in CS3 and uses the timeframe which is not exist in pure ActionScript.
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
import myclasses.Cover;
public class Prototype extends Sprite {
protected static const WIDTH:int=3;
protected static const HEIGHT:int=2;
protected static const SPACINGX:int=100;
protected static const SPACINGY:int=74;
protected static const OFFSETX:int=96;
protected static const OFFSETY:int=100;
protected static const SIZE:Number=100;
protected static const COLOUR:uint=0x999999;
[Embed(source="images/pic1.jpg")]
protected static const PIC1:Class;
[Embed(source="images/pic2.jpg")]
protected static const PIC2:Class;
[Embed(source="images/pic3.jpg")]
protected static const PIC3:Class;
protected var imagesList:Array=[PIC1,PIC1,PIC2,PIC2,PIC3,PIC3];
protected var X:int;
protected var Y:int=27;
protected var count:int;
//protected var firstTap:Class;
//protected var secondTap:Class;
public function Prototype() {
var shuffled:Array = shuffleList(imagesList.length);
for(var i:int; i<imagesList.length; i++) {
//var colour:uint;
//colour=0x999999;
var j:int = shuffled[i];
var thing:Sprite=new Sprite();
thing.addChild(new imagesList[j]());
thing.x=X;
thing.y=Y;
addChild(thing);
new Cover(this,X,Y,SIZE,COLOUR);
X=X+SPACINGX+OFFSETX;
count++;
if(count == WIDTH){
Y=Y+SPACINGY+OFFSETY;
X=0;
}
addEventListener(MouseEvent.MOUSE_DOWN,selectImages);
}
}
public function selectImages(event:MouseEvent):void {
//(P/S: this is not the actual code)
var target:Sprite = Sprite(event.target)
if(firstTap == null){
firstTap = ; //1st selected image
removeChild(target);
}else if(secondTap == null){
secondTap = ; //2nd selected image
if(firstTap == secondTap){
firstTap = null;
secondTap = null;
}else{
//firstTap = ; //cover back
//secondTap = ; //cover back
secondTap = null;
firstTap = ; //selected another image
}
}
}
protected function shuffleList(n:Number):Array {
var startList:Array = new Array(n);
var endList:Array = new Array(n);
var i:Number, j:Number;
for (i=0; i<n; i++) {
startList[i] = i;
}
for (i=0; i<n; i++) {
j = Math.floor(Math.random()*startList.length);
endList[i] = startList.splice(j,1)[0];
}
return(endList);
}
}
}
Please help me figure out. Thanks.
Well I didn't really go through your code in details, but from looking at it, it seems you are making things really complex. So let me give you a hint in how I would do it...
1) First I would make a 'card' class, which extends sprite or bitmap, mainly containing the image of that card, image of the cover/mask, some animtion methods like hide/show e.t.c, and possibly an 'id' variable to recognize it later, though that is not needed. You can also get away with the array you have, and in that case, skip step 2.
2) Now push two copies of each card in an array.
example [new card('c1'),new card('c1'),new card('c2'),new card('c2'),.....].
3) Now comes the part where you made it most complex, that is, the shuffling of the array. Let's write a custom function for it, shall we?
function shuffleArr(arr):Array
{
var len:int = arr.length();
for(var i:int=0; i<len; i++)
{
//Swap the value at i with a random value within the array;
var tmp_pos:int = Math.floor(Math.random()*len);
while(tmp_pos==i)
{
tmp_pos = Math.floor(Math.random()*len);
}
var tmp_var:card = arr[tmp_pos];
arr[tmp_pos] = arr[i];
arr[i] = tmp_var;
}
}
4) Now that the array is shuffled, you simply have to lay them out in a grid.
for(var row:int=0; row<6; row++)
{
for(var col:int=0; col<6; col++)
{
card_arr[i].x = card_arr[i].width*cols+5;
card_arr[i].y = card_arr[i].height*row+5;
stage.addChild(card[i]);
}
}
5) Now you have to check for user click and take action, and there are many ways to do it, but I will tell one of them...
a) Give the cards a click event handler, this becomes easy if the cards are a class, or you can look into event.target property and use a general click handler. it's up to you.
b) On click, push the card's id in an array. If you did make them into a class, their ids should now be, c1, c2, e.t.c, and you can do
holder_arr.push(this);
this.removeCover();
6) Now you have to make sure, that the holder array can only hold two values at a time. Then do the checking. I am writing a semi-pseudo code with a lot of assumed functions and values:
//Insert
if(holder_arr.length()==2)
{
//flip back the cards and empty the array
holder_arr[0].showCover();
holder_arr[1].showCover();
holder_arr = [];
}
holder_arr.push(this);
...
..
7) For checking make a function and run it every time a card is clicked, and also when a timer ends, to flip back the cards.
function checkCards()
{
if(holder_arr.length==2)
{
if(holder_arr[0].id==holder_arr[1].id)
{
//the cards match
holder_arr[0].vanishAnim();
holder_arr[1].vanishAnim();
holder_arr=[];
}
else
{
holder_arr[0].showCover();
holder_arr[1].showCover();
holder_arr=[];
}
}
}
Obviously you will remove the cards from the actual card_arr too, but when to do that is up to you to figure out ;)
Personally , I find the problem has more to do with the way you shuffle your cards as it makes it a bit more difficult to identify what card is what.
Let's say for instance that instead of shuffling your embed assets , you were first creating your cards , naming them after the image they add , then creating an Array ( or Vector ) of cards and shuffle that Array ( or Vector ), identifying the cards would be fairly easy since you'd only have to compare their name property.
//PSEUDO CODE
- create Array ( Vector ) of embed assets [PIC1, PIC2 , PIC3]
- create cards and use Array ( Vector ) index to identify
each card with the name property
- create a set of six cards
- shuffle set