Scripting Creation of Prefab... I have it wrong somehow.

Hi,

I’m new to Unity, but have been programing for years.

I created 6 different Prefab “Blocks”. I also created a Script with the following Code that I attached to the Main Camera to be able to test the the Blocks looked correct once created, right now the Prefab and textures are just public and I set them in the Inspector.

Now I want to be able modify this Script so that another script can create multi blocks of different types and locations by passing in the Prefab, and location into this script. However I cant seem to figure out how to pass in different Prefabs to tell this script what prefab to create this time.

I wanted something like
Block(Prefab1, locationx, locationy, locationz);
Block(Prefab2, locationx+1, locationy+1, locationz+1);
…

But I cant figure out how to that. I just want a way that I can have another script pick the type of “block”(Prefab) and textures and location, and then have this script go off and create it… Maybe I’m looking at it the wrong way or maybe I need to attach this script to each of the prefabs, and create the prefab from the high up script?! I don’t know, I need help.

i’m not sure if i understand you correct. but when the other script already knows which prefab to instantiate and where it could do this on its own and not passing this to this script. but if you need it this way (for example to manage all blocks) look at the example.

in the calling script you also define a public Transform drag the prefab on it and pass it as a function parameter. you can also dynamically load prefabs with resources.load or maybe somehow with assetbundles.
you could also create a public array of prefabs in this script which can be filled in the inspector and only tell in a function which index to instantiate and where.

Transform[] blocktypes;	// fill the slots in inspector by drag + drop

public void CreateBlock(int index, Vector3 position, Quaternion rotation)
{// call this function from the other script
  Instantiate(blocktypes[index],position, rotation);   // store the return valu to acess the block later
}

but you need to find the camera to access this script or carry a manual reference at every possible caller.

hope that helps a bit.

Thanks I will give this a try tonight, It looks like something I already tried and kept telling me it didn’t know how to convert Transform[ ] to Transform, but maybe I had something different then the way you have it as I would like your method to work.

Edit: Thank You, I thought I had tried the Array Idea already and never got it to work, but using your code above it works!! THANK YOU.

sounds like you wanted to instantiate the whole array not one position out of it.

Yea, I dont know what it was that I had wrong…

On another note, one of my many failed trys last night I had created the 2nd script that would be creating all the different blocks. I added a constructor to the Block Class that would take in an int Prefab(for the array), and then some more information for position and such. However when I went and did a Block A = new Block(3 … ); it said cant do a new on a monoBehavior, so I tried taking that part out of the class, but then it said it couldnt instantiate or something like that. What do I do, what am I missing?

classes derived from monobehavior cant be instantiated via constructor. simply use instantiate and provide a initialize method which is called afterwards on the object.

If I do it that way the Init function would do whatever the constructor would have done. What about the Start and Update Functions would I still have those functions or would they go away if its not a Monobehavior? If they would still be called what order would they be called in, can I make sure the init function is called before Start? I guess the other option is the make the Init function do both what I would have done in the constructor and what I have in the Start. with still being new to Unity what is the best way to handle this?

if thats a question: yes.

if your class does not derive from monobehavior you can have functions called start + update but they are not called by the engine automatically. monobehaviors should be added to gameobjects and handle engine events (ongui, oncollide, …). your own “data” classes can store + handle stuff not related to a certain game object. you could for example have a manager monobehavior utilizing an update function and checking user input there and distributing it to several objects beeing non monobehaviors and managed by it. or you make everyone of these objects a monobehavior. depends on what you need + prefer and how the objects shall interact.

they are not called. after instantiation awake is called first, then start and then your init function.

so you have to decide if a class should derive from monobehavior or not. i usually put a “script” suffix at the former and a class suffix at the latter to distinguish between them.

read (also the links): What is the general use of Awake(), Start(), Update(), FixedUpdate(), LateUpdate()? - Questions & Answers - Unity Discussions

edit for clarification:
the mentioned init method for a monobehavior derived class is not called automatically. its just a workaround that you cant pass parameters with instantiate other than position + rotation.

Transform newobj = Instantiate(prefab, new Vector(0,0,0), Quaternio.identity);
Scriptname script = newobj.GetComponent<Scriptname>() as Scriptname;
script.Init(param1, param 2); // do what you need for initialization here in your own defined method

as you see you need to retrieve the right script component and a gameobject can have several scripts attached. thats also the reason why you cant simply use new for your scripts as they are atteched to a game object and only exist in conjunction with it.

Maybe it would be easier to exsplain what I’m trying to get at big picture…

I’m wanting to create a randomly generated world made up of blocks somewhat like Minecraft. However I have 5 (and will most likey create more) Prefabs for different shaped blocks depending on what the block is and what blocks are around them. So the world will be stored as an array of block types. From the block type and information from the blocks around the current block I want to pick a prefab block and add the needed textures and lighting and such to it and have it be created in the world.

My thought was to create a block class that can create itself, and apply the textures and such, but it needs to know from a higher level for what prefab it should use and lighting and posistion in the world as it would be up to a “chunk” manager as I think they called it some other examples I saw, to know the blocks around the current block to be able to determe the correct shape and lighting for this block.

This is the general point I’m after, and I figured each block would know how to apply its own texture and lighting. Maybe the prefab creation (picking the type or prefab and location) should be handled by this “Chunk” Manager and each prefab should have scripts for applying the lighting and textures and things? I dont have a great understand of all of Unity so I dont know the best way to layout a project like this. I want the land to be dynamic/modifable by players and explosions and or events and things like that as well. I have been layout out like I would if it was all software and everything was just classes, but maybe with Unity I need to lay it out differently?

Based on your clarification edit it sounds like i should update the Block Script to be part of the Prefabs, and then have the “chunk” manager higher level script be the one to create the prefab at the correct location, and just call in to the Block script to get to update its texture and lighting.

With that model how does the physics come in to play, when something blows up does unity figure out what happens, or do we have to write the logic for that. What does Unity do and what do we have to do in relation to physics and collisions and explosions and things?

I should most likey work on one thing at at time, but I feel like I need to get a better understanding of how Unity works before going forward with a loayout.

certainly ;).

search the forums. there are many threads to this topic. i can only suggest as you run into memory/unity limitations quickly to use an optimized approach to place blocks. i would check at each six side of a cube if there is another solid block. if so you dont need to instantiate this block as it cant be seen/touched and you only have the surface covered with blocks. once a block is removed or added repeat this for all adjacent blocks. also you may have look at pooling to reuse not needed blocks to avoid destroying and instantiation. and some kind of spatial tree (quadtrees, octrees) structure to fade out large groups of blocks which are not visible to the player.

you dont need to add textures manually to each block when they are the same for each type. simply do this for your blockprefab once and then just use it. lighting is done by unity automatically so you may just adjust material/shader parameters for your prefab and add the lights to your scene. if you need to specialize your prefab in some kind consider doing more types when they are countable and not “unlimited”.

a prefab cant instantiate itself as its code is not on an active gameobject and thus is not executed. so i would have said manager class creating the world randomly in a function (filling the 3d array) and then instantiate/spanwfrompool the prefabs according to the stored type. a block just contains its own behavior and should send a message to the manager once it is removed/placed so the manager can do required work for the surrounding blocks (fe place new blocks around when one has been removed as i suggested dont have blocks which are not visible).

as i said usually you do this in the prefab definition already and dont need it to set it by hand afterwards.

a manager is required imo as the blocks dont exist independant from each other but have relations and actions to perform for many blocks (blend them out when not visible etc). and when you define textures for each prefab type you dont need to do it later (although you can and must if you reuse blocks for example).

as suggested read the threads about this topic in the forum. and also do some tutorials to learn the “unity way” as its a bit different (and better imo) than other engines handle things.

unity is component based so you have almost no inheritance or deep class hierarchies. let a component/script handle a certain aspect of your game and add it where required.

right.

i dont see necissity for this when you define your prefabs accordingly.

usually you add a rigidbody to an object to be handeled with physics but this way your blocks will simply fall together. if a block has a collider the player can walk on it and collide with it and it keeps its position until you (re)move it. i have not played minecraft so my understanding may be wrong but i think you dont want real physics for unreal behavior.

explain what you mean with physics please. collisions are handeled by colliders (or rigidbodies). explosions are your own thing so you make an explosion prefab, add a sphere collider to it which gets larger each frame (or check spherecastall), check the objects inside it and apply some damage to them or what you need (you can also move them but this will make your worldarray almost useless i guess.

that sounds like a big project and you should definitely learn about the unity basics first before start it. you could too easily get lost or do things in a suboptimal way and have problems later on.

I have read alot of the thread about minecraft worlds, and looked at some of the downloadable examples. My problem with them is they only create a mesh to create the top layer that you see and walk on, but I want blocks that can interact with the Unity Engine for collisions and exsplosions, and making block fall if placed in locations that cant support it and things like that. The examples I have seen like i said seem to only create a top mesh for walking on, and change the mech as you change the block under it. With that kind of implementation I didnt see a way to add the collisions and explosions and things that I wanted. I dont want to have to write all the physics interactes I wanted Unity Blocks that would follow Unity Physics.

I did add mesh colliders to my prefabs, but not rigidbodys…
I guess I will read up on rigidbodys and colliders and make sure I understand how they relate to eachother and in relation to how Unity does its different physics things.

Thank you very much for the help, it seems I was not as ready to start as I thought I was…

when an explosion destroys a block remove it and place another one behind it and let it be hit by the schockwave (and maybe also destroyed). i cant imagine if that behavior is expected by the player and fun for him. as i told this is not my type of game.
for falling etc you can also add rigidbodys at runtime (or enable them) to a certain block and let it fall with gravity or thrown away by explosion. but i already asked how you want to synch that with your typearray which makes up your world.

you can try that. i have seen physics demos of unity with approx several hundred of objects. but if this runs on slower computers and if these amounts fits your needs is a question for you.

glad i could be of help. good luck anyway with your project. but i fear you must make some cut backs from your requirements or do heavy optimization for this to run (in any engine) because its a relatively advanced topic imo.

I think I can pull it off, from reading some more I want each cube to have a collider and a rigidbody, but most of the time the cubes will be “rigidbody.isKinematic = true;” aka Static. If something happens that I need to check physics on a block(new block is placed, or old block is removed) (or in the case of an explosion some number of blocks in a radius around that explosion) I can trun that Kinematic to false, let the Unity engine do its thing, and then turn Kinematic back on.

As for the synching with my array, the blocks would have to get “cleaned up” after an explosion and “snaped” in to a empty normal block location. Not sure how to make that step look good for the player but that is for a MUCH later time frame. (Or maybe it would snap back once the player left the area or saved the world so the next time it would generate the block is little different way, but in a correct grid location… more testing must be done!)

I think I have much better understanding of how Unity works thanks to you. I still have many more tests to run to make sure I can make things work the way I want, but this gets me much closer to the right track!