_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | How would I apply force to a bullet in 2D? I wrote the code below in order to try to get a bullet to fire at a specific angle for my top down shooter. However when I press space the bullet just spawns in front of the game object despite it having a bullet speed. I made sure that my bullet prefab has a rigidbody and I am calling to it in my script. using System.Collections using System.Collections.Generic using UnityEngine public class FireAway MonoBehaviour private Vector3 mouse pos private Vector3 object pos private float angle private float bulletSpeed 1 public GameObject ammo private Rigidbody2D rb2D void Start() rb2D ammo.GetComponent lt Rigidbody2D gt () Update is called once per frame void FixedUpdate() Point the cannon at the mouse. mouse pos Input.mousePosition mouse pos.z 0.0f object pos Camera.main.WorldToScreenPoint(transform.position) mouse pos.x mouse pos.x object pos.x mouse pos.y mouse pos.y object pos.y angle Mathf.Atan2(mouse pos.y, mouse pos.x) Mathf.Rad2Deg 90 Vector3 rotationVector new Vector3(0, 0, angle) transform.rotation Quaternion.Euler(rotationVector) if (Input.GetKeyDown("space")) GameObject BulletPlayer (GameObject)Instantiate(ammo, transform.position, transform.rotation) bullet.transform.LookAt(mouse pos) rb2D.AddForce(BulletPlayer.transform.forward bulletSpeed) |
0 | Lightmapped prefabs for procedural content I'm doing a game with procedural content from handmade prefabs, but I ran into a problem as Unity bakes the scene instead of objects when lightmapping with Beast. So when the prefabs are instanced they are without lightmaps. Is there a way to get lightmaps for dynamically created prefabs with Unity's built in lightmapper? |
0 | Unity blocked after changing Time region I reinstalled Windows then Installed Unity. Then I changed my timezone from US Pacific to Europe where I actually live. Unity got blocked "Expired licence" even though I use the free version. https forum.unity.com threads expired license on free version.90072 If I change my timezone back to US Pacific Unity works (Took me 2 hours to figure out it was the timezone btw). I tried reinstalling Unity from scratch, didn't work. How can I change timezone back to Europe without locking up my Unity licence? |
0 | Unity Camera Moving Vertical So I want to make a smooth transition with the camera from point A to point B while keeping direction and rotation. My current approach is using Vector3.Lerp using UnityEngine public class CameraMoveVertical MonoBehaviour public float cameraSpeed 0.125f public void moveCamera() Vector3 lerpPosition Vector3.Lerp(transform.position, new Vector3(transform.position.x, transform.position.y 50, transform.position.z), cameraSpeed) transform.position lerpPosition The camera does move but the movement is instant. Any way to make it a smooth transition? |
0 | Help to Code Bowling Like Feature in Unity for Mobile I need Code or Guidelines for Touch Feature. When We Drag ball back and Send it Forward. I am Making feature like bowling, and I need Player to add force while dragging back and also curve the path of the Ball Anybody, Please Help |
0 | How UV channels work in Unity? So this Graph Shader is using UV0 channel As far as I know, UV layout in a 3d model file (e.g. fbx) is stored inside the model itself, is that right? But the picture above implies that a model can contain multiple UV channels inside of itself. Is that true? |
0 | How can I let players "scrape away" one texture to reveal another? In this game I'm making, I want my players to be able to remove rust from an object based on collisions from another object such as a wire brush. Since it's a VR game, performance is key. I've been having a hard time getting on the right track I think I'm not asking the right questions. The closest I've gotten was a video about making a scratch off lotto ticket. Someone in the comments to that video says Good Idea. But, this isn't practical for any real world apps. It instantiates too many gameobjects. There are better more efficient ways of achieving this effect using shaders or render texture. They don't really expand on that further, but I did do a little more searching to see how I might do this using shaders. I found this video about using replacement shaders, but I'm still not sure if that's the right track. I don't know If something like that is the smartest way to do it. I'm basically a complete noob when it comes to shaders and textures so this is new territory for me. I apologize if this is a duplicate question, I've tried searching but haven't found anything quite like what I'm looking for. Please let me know if there's anything I can explain further, and any help that gets me pointed in the right direction would be greatly appreciated. |
0 | How do I create textured landscape in low poly style? I'm trying to create something similar to this kind of artistic landscapes in Unity. I've been from trying to use Unity's terrain system and Gaia to making it in Blender no matter how I can't figure out how it's made how to texture it afterwards. I'd be thankful is someone can point me in the starting direction. Thanks ! |
0 | Automatic audio segmentation and find the most energetic segments What algorithm can be used for audio segmentation? I want to divide song to segments and find the most energetic segments (begin and end in seconds). It is needed for the rhythm game. Examples https soundcloud.com dieantwoord yolandi die antwoord cookie thumper (most energetic segments first 3 09 3 38 second 5 02 5 27) https www.youtube.com watch?v StZcUAPRRac (rammstein sonne) (most energetic segments first 0 55 1 20 second 1 52 2 44) |
0 | Unity 3D Imported Assets Rotated Backwards in game I'm putting together boilerplate for a Unity FPS game, and having an issue with importing an Asset Store model. All of my weapons are asset store prefabs. I'm new to Unity, but this makes me think there's something about the imported prefabs themselves that's setting the axis alignment of the models in game. Anyone know what I'm missing to fix this and rotate that model in the world (without just writing a model script to rotate it programmatically every time) ? |
0 | How to obtain a camera stream from Unity without rendering it to the player's screen? I'd like to stream the output of two cameras to a separate process. Right now, it looks like the best way to do that is to grab the rendered camera views from the screen via platform specific screen capture hooks then compress them real time with h.264. Is there a way to grab the input of the cameras within unity and avoid rendering them to the screen? One solution I'm considering involves using Unity's multiplayer capability to run the game on a separate machine and grab it from that screen buffer, unbeknownst to the player. |
0 | how to recieve a trigger with collider or recieve a trigger with collider in unity i know if your object has a Collider you can sense another Collider with OnCollisionEnter function or... and you can sense another collider with trigger with OncollsionEnter function and... but i want to sense other object with trigger even with collider or even with trigger. i cant sense otherobjects that have triggers. for example i have bullet that as i dont want to collider have any physics i turned it to trigger but how can make a charcter to sense it? Thank you for helping |
0 | Is there any way to move the sprites inside the sprite editor? I have imported a .png file of a stickman in which I had placed his head, body, two legs, and two hands a bit far apart from each other so that Unity will automatically convert the picture into sprites. Indeed, Unity did convert those body parts into sprites easily but now I have a problem. I made a bone going through the body and another bone going from the body to the head through the transparent area in between the sprites. Also, I have created one bone for each hand and leg and parented them to the bone in the body. The problem is that when I automatically generate geometry then the mesh rendering works completely fine within the body of the stickman, but it doesn't work anywhere else, be it the hands, or the head, or the legs. I can see the mesh only in the body of the stickman and nowhere else. Does this problem arise because the sprites are not connected, or is there any other reason? I am very new to game development, therefore please try to explain it in simple words. Thank You. |
0 | Changing the origin pivot point of the parent in Unity I create a game object, add some children to it, and would like the pivot point of the parent to be somewhere inside the area occupied by the children, not far away in the scene. Like in the example below, I have three blocks of platforms situated near each over. I add them into a parent, then try to move that parent and notice that the origin point of the parent is actually not somewhere between its children, but outside them on the upper right Does someone know a way to change the origin point in such case? |
0 | Trees made with Unity's Tree Editor have 2 sides 1 bright and 1 normal (The directional light lits the side shown at the right side of the picture.) I tried changing shaders, but that just makes the bright side fully dark. I tried changing Ambient Occlusion but that make the normal side fully dark, and the bright side normal. I use the "Green Forest" (free) asset from the Unity Store. Currently it uses the "Hidden Nature Tree Creator Leaves Optimized" shader. Some types of trees got fixed by turning off AO, and setting shadow strength to 0 both at the shader and at the Tree component, but for example the tree on the picture can't be fixed for some reason. One type got fixed by setting its shader to "Tree Creator Leaves Fast". But that way shadows "float" around the leaves. Why does this happen? |
0 | Unity crash upon opening a specific scene I have this one specific scene that I spent over 20 hours building. But as of today when I attempt to open it unity crashes. I have opened the error log and it states Unity.exe caused an Access Violation (0xc0000005) in module Unity.exe at 0033 4150123b. Error occurred at 2017 09 22 200636. C Program Files Unity Editor Unity.exe, run by MarcR. 62 memory in use. 16257 MB physical memory 6165 MB free . 32641 MB paging file 18590 MB free . 134217728 MB user address space 134213224 MB free . Read from location 00000098 caused an access violation. I have tried running the program as administrator, updating the unity editor and cleaning the cache. The funny thing is that I am actually able to open the scene additive to my current scene. Can anyone tell me whats going on? (On an end note I did not want to post ALL of the error log if you need to see please comment and I will, of course, link it) |
0 | Bullets doesn't do any damage I have a melee enemy tagged as enemy. enemy has two coliders a capsule(physics) and a sphere(for attacking player in radius and istrigger) and a particlesystem, enemy has enemyhealth script attached. Similarly, bullet has capsule collider and set istrigger, I've attached enemyhealth script to bullet as enemy sphere and bullet capsule are triggers (bullet doesn't have any particle system need fix for this too without raycast), bullets are destroyed on colliding with enemy but doesn't damage the enemy. script used for enemy health using UnityEngine using System.Collections public class enemyhealth MonoBehaviour public int health 40 public int current public int score 10 public AudioSource deathclip public ParticleSystem death CapsuleCollider Collider bool dead Use this for initialization void Start () deathclip GetComponent lt AudioSource gt () Collider GetComponent lt CapsuleCollider gt () death GetComponentInChildren lt ParticleSystem gt () current health dead false void Update() public void Takedamage (int amount ) if (dead) return current amount if (current lt 0) die () void die () GetComponent lt NavMeshAgent gt ().enabled false dead true Collider.isTrigger true deathclip.Play () death.transform.parent null death.Play () Destroy(death.gameObject) Destroy(gameObject) script used for bullet using UnityEngine using System.Collections public class mover MonoBehaviour public float speed public int damage 10 enemyhealth Enemyhealth GameObject ENEMY bool enemyinrange Use this for initialization void Awake () GetComponent lt Rigidbody gt ().velocity transform.forward speed Enemyhealth GetComponent lt enemyhealth gt () ENEMY GameObject.FindGameObjectWithTag ("enemy") void OnTriggerEnter(Collider other) if(other.gameObject ENEMY amp amp Enemyhealth.currenthealth gt 0) enemyinrange true Destroy(gameObject) void OnTriggerExit(Collider other) if (other.gameObject ENEMY) enemyinrange false void Damage() Enemyhealth.Takedamage (damage) Update is called once per frame void Update () if (enemyinrange) Damage () |
0 | Position orient parent to place child at a particular position orientation I have a GameObject for which I know its world position and rotation. From another app, I receive a new rotation and position, which should represent the local position and rotation of my GameObject. How can I compute the position and rotation of the parent object knowing the (world) position, the (world) rotation, the localPosition and the localRotation of its child? How can I find the necessary transform to obtain the second pair of coordinates from the first pair of coordinates? |
0 | Unity Raycast not detecting layers I am having problems with layers detection using raycasts. Context I created a grid to use in a pathfinding algorithm on a 2D plane. I want to implement now different weights according to the layer each node of the grid is in e.g. a node in a normal terrain will have a "terrainPenalty" of 1 and more difficult terrains 2 or more. In order to detect the terrain type on the 2D plane, I am shooting a raycast on the node position for each node previously considered "walkable". The problem comes up now, because I observed that the paths created are neglecting such values, this is the slice of code which is giving me problems if (walkable) Ray ray new Ray(worldPoint Vector3.back 10, Vector3.forward) PROBLEM HERE (NOT DETECTING PENALTIES) RaycastHit hit walkableMask walkableMask if (Physics.Raycast(ray, out hit, 100, walkableMask)) walkableRegionsDictionary.TryGetValue(hit.collider.gameObject.layer, out terrainPenalty ) At first I thought that the problem was how the layers were called, because I created a LayerMask combining 2 layers using the bitwise OR operator, but then I tried to play around with all the layers (hence why there is walkableMask walkableMask now). The result was always a false output for Physics.Raycast(ray, out hit, 100, walkableMask). I thought that maybe I was getting the wrong coordinates for the ray, but I created some gizmos to actually check that the ray was piercing perpendicularly my plane and it did, as well as trying to change layers to see if anything worked, but the output is always false. What am I getting wrong? Here is the rest of the function, if needed I can upload the whole script as well void CreateGrid() grid new Node1 gridSizeX, gridSizeY Vector3 worldBottomLeft transform.position Vector3.right gridWorldSize.x 2 Vector3.up gridWorldSize.y 2 for (int x 0 x lt gridSizeX x ) for (int y 0 y lt gridSizeY y ) Vector3 worldPoint worldBottomLeft Vector3.right (x nodeDiameter nodeRadius) Vector3.up (y nodeDiameter nodeRadius) bool walkable !(Physics2D.OverlapCircle(new Vector2(worldPoint.x, worldPoint.y), nodeRadius, unwalkableMask)) bool walkable !(Physics.CheckSphere(worldPoint, nodeRadius)) int terrainPenalty 0 if (walkable) Ray ray new Ray(worldPoint Vector3.back 10, Vector3.forward) PROBLEM HERE (NOT DETECTING PENALTIES) RaycastHit hit walkableMask walkableMask if (Physics.Raycast(ray, out hit, 100, walkableMask)) walkableRegionsDictionary.TryGetValue(hit.collider.gameObject.layer, out terrainPenalty ) grid x, y new Node1(walkable, worldPoint, x, y, terrainPenalty) EDIT Here is how I create the layerMask foreach (TerrainType region in walkableRegions) walkableMask.value region.terrainMask.value is the bitwise OR operation, I could have simplified by writing " " walkableRegionsDictionary.Add((int)Mathf.Log(region.terrainMask.value, 2), region.terrainPenalty) Where TerrainType is the following class System.Serializable public class TerrainType public LayerMask terrainMask public int terrainPenalty I basically create an array of TerrainType objects that will store their layerMask and penalty and then upon positive output from the raycast I access the dictionary to retrieve the terrain penalty. For the terrain and obstacles I am using a 2D BoxCollider and 2D PolygonCollider respectively, they do not interact with any other layer. Thanks for any possible hints, I don't know what else to try . |
0 | How to add constant force to player with sperical gravity planet.? I have a planet and character. My player move perfect around planet with pressing key like 'w','s','a and 'D'. I want to move my player on every frame with same force around sphere. I try plane surface constant force code like this this.rigidbody.AddForce ( 3f,3f,3f) , when start playing game this code work fine but after some movement it stop my player on specific position of planet. I want to use this code for 3D sphere. Any one can help me how can add constant force to my player on 3d sphere.? I want add constant force to player when game start. I don't want any kind of planet's orbits, because my player is moving on all over the planet. I try below link but it did not working for me. How can i accurately simulate orbits in unity.? Here is my Sctipts PlayerController.cs using UnityEngine using System.Collections public class PlayerController MonoBehaviour public float moveSpeed 10 public Vector3 moveDir Rigidbody rigidbody Update is called once per frame3 void Start() rigidbody GetComponent lt Rigidbody gt () void Update () moveDir new Vector3 (Input.GetAxisRaw("Horizontal") ,0,Input.GetAxisRaw("Vertical")) void FixedUpdate() rigidbody.MovePosition (rigidbody.position transform.TransformDirection(moveDir) moveSpeed Time.deltaTime) FauxGravityBody.cs using UnityEngine using System.Collections RequireComponent (typeof (Rigidbody)) public class FauxGravityBody MonoBehaviour public FauxGravityAttractor attractor public Transform myTransform Rigidbody rigidbody Use this for initialization void Awake() this.rigidbody GetComponent lt Rigidbody gt () void Start () myTransform transform rigidbody.useGravity false rigidbody.constraints RigidbodyConstraints.FreezeRotation Update is called once per frame void Update () attractor.Attract (myTransform) FauxGravityAttractor.cs using UnityEngine using System.Collections public class FauxGravityAttractor MonoBehaviour public float gravity 10 public void Attract(Transform body) Vector3 gravityUp (body.position transform.position).normalized Vector3 bodyUp body.up body.GetComponent lt Rigidbody gt ().AddForce (gravityUp gravity) Quaternion targetRotation Quaternion.FromToRotation (bodyUp, gravityUp) body.rotation body.rotation Quaternion.Slerp (body.rotation, targetRotation, 50 Time.deltaTime) I am working with this scripts, If any one help me? then please. |
0 | How can I make the loop only once when it's inside OnGUI? The script is EditorWindow type. private void OnGUI() var selections Selection.objects.OfType lt GameObject gt ().ToList() if (selections.Count gt 0) for (var i selections.Count 1 i gt 0 i) var selected selections i transformSelection.Add(selected.transform) TransformSaver.SaveTransform(transformSelection.ToArray()) tempTransformSelection transformSelection transformSelection new List lt Transform gt () When I select with the mouse a object in the Editor Hierarchy it will keep making the loop nonstop since selections.Count is large then 0. I tried to add after the loop selections new List lt GameObject gt () But it didn't help. I want that it will make the loop and the whole code inside the if (selections.Count 0) only once each time when selecting one or more objects in the editor. If I select one object make the whole code once if I then selected another more object make the whole code over again for the two selected objects and so on but make it once. Now it will keep making the loop over and over again even if I didn't select more other objects. Since in the editor the first object is still selected it will keep making the code the loop over and over again. This is what I tried var selections Selection.objects.OfType lt GameObject gt ().ToList() if (selections.Count gt 0 amp amp isSelected false) for (var i selections.Count 1 i gt 0 i) var selected selections i transformSelection.Add(selected.transform) TransformSaver.SaveTransform(transformSelection.ToArray()) tempTransformSelection transformSelection transformSelection new List lt Transform gt () isSelected true The flag boolean isSelected is global variable and set to false as init. UPDATE what I tried var selections Selection.objects.OfType lt GameObject gt ().ToList() int currentSelectionCount selections.Count if (currentSelectionCount ! lastSelectionCount) lastSelectionCount currentSelectionCount for (var i 0 i lt currentSelectionCount i) var selected selections i transformSelection.Add(selected.transform) TransformSaver.SaveTransform(transformSelection.ToArray()) tempTransformSelection transformSelection transformSelection new List lt Transform gt () Selection.objects new UnityEngine.Object 0 But when I select object in the editor in hierarchy it's immediately unselecting the object since the line Selection.objects new UnityEngine.Object 0 |
0 | Photon Realtime, StripKeysWithNullValues cause heavy GC Alloc In our current project, we use Photon room properties to sync entities. and i noticed some heavy GC Allocs while deep profiling the game and it always ends down to this method. Have anyone faced this issue before ? or attempted to fix it ? here is the source code of that method. lt summary gt This removes all key value pairs that have a null reference as value. Photon properties are removed by setting their value to null. Changes the original passed IDictionary! lt summary gt lt param name "original" gt The IDictionary to strip of keys with null values. lt param gt public static void StripKeysWithNullValues(this IDictionary original) object keys new object original.Count original.Keys.CopyTo(keys, 0) for (int index 0 index lt keys.Length index ) var key keys index if (original key null) original.Remove(key) |
0 | Unity directional light for a day night cycle on a hex sphere So I am trying to create a Day Night cycle on a sphere but it doesn't work the way I want it to. As the model is hex tiled, you see the edges of the hex tiles also lit up like below. I am using a directional light source for the same. I don't want the above effect. I want it to ignore the edges and just be a straight line instead. Something like below Is there a way inside Unity that I could achieve this effect just using the lights? |
0 | Enum or Inheritance for event based interaction? I am currently considering two possibilities to a centralised interaction system within my game. Consider that you want to produce different results for different types of objects within the game world you interact with a signpost and dialogue appears, or interact with an item on the ground and it gets added to your inventory with a notification. Essentially, I cannot decide whether it would be more efficient to implement such functionality all within one centralised place or to spread each function out over separate events. Option 1 Centralised This is what I have started coding. One Interact class which contains several "Types" of possible events in my game. When the player "interacts" with an object implementing this script, it will implement the functionality that it is set to in the Editor. This means I drag and drop this Event Script onto a prefab and can automatically tweak its functionality within a couple of seconds and have it ready to go in the game world. I have simplified the general consensus of my code into this block for readability public string eventName public enum EventType Movement 0, Dialogue 1, NPC 2, ItemCollect 3, Teleport 4, Cutscene 5, Switch 6, Custom 7 public EventType eventType INITIALIZATION private void Awake() SetupEvent(eventType) public void Activate(bool calledFromTrigger false) if (autoTrigger amp amp !calledFromTrigger) return Debug.Log("Activated " name "!") StartEvent(eventType) private void StartEvent(EventType type) switch (type) case EventType.Movement MovePlatform() break case EventType.Dialogue break case EventType.NPC break case EventType.ItemCollect break case EventType.Cutscene break case EventType.Switch break case EventType.Custom break Resulting in Option 2 Inheritance It is as if I have a little devil and angel on my shoulder, one tugging me towards the easy and half finished code of the former example, and another urging me to redesign what I am doing into a much cleaner and abstracted approach. In the previous example, all "event types" (Movement, Dialogue, Item Collection etc.) were handled by enums that were passed through a Switch statement to check which method should be executed based on the parameters inputted into the Unity Editor for that specific Game Object. In this system, there would be a base "Interactible" class, which various classes would inherit from to implement functionality. The Activate() method would be overridden in the children for each specific class. public class NPC Interactible public override void Activate() NPC Code... The unfortunate downside to this is that I can't just use one prefab for all my events and change them based on the custom editor that I define. I would have to create a custom editor for each possible child of the Interactible class, and instead of selecting which type of event I want it to be from a simple drop down, I will have to swap out different scripts for different functionality. |
0 | Border around game preview window I'm trying to put my game view and scene view next to each other, but the game window seems to have a border around the actual game view that I can't remove In the screenshot above, the game view should be touching the sides. I've tried changing the aspect ratio setting at the top to no avail, increasing the scale works to remove the border but that also zooms in so isn't a correct representation of the game. Does anyone know how I can remove this border? |
0 | Unity Anti aliased Edge Shader with Variable Thickness (does not require standard shaders or post processing) I'm trying to create a coloring book effect for an edge shader (not an outline shader) but having some difficulty creating straight line shaders that don't look badly anti aliased. (Even before getting to the variable thickness on the lines part) The solutions I've found seem to reference Vectrosity or post processing stack. Is such a thing as a shader (not post processing level) edge shader not possible? |
0 | How can I render extremely large models? I'm trying to build a game in Unity similar to the game Kerbal Space Program where there are large celestial bodies that the player can orbit. I'm running into a few problems though. My first issue is that the larger I make a sphere, the slower the game gets. Secondly, whenever the sphere exceeds a certain size, the rendering engine cuts off part of the planet, which means I can only see half the model. How can I do this at the size that KSP has? |
0 | OnCollisionEnter calls rapidly bool tntFall true void Awake() tntFallTime Time.deltaTime 0.05f void OnCollisionEnter(Collision coll) if (CurrentScene ! "ColorGame" amp amp CurrentScene ! "PaintingGame" amp amp coll.gameObject.tag ! "Player" amp amp CurrentScene "TNT Run" amp amp tntFall) Debug.Log(coll.gameObject.GetComponent lt MeshRenderer gt ().material.name) if (coll.gameObject.GetComponent lt MeshRenderer gt ().material.name "TNT 0 (Instance)") coll.gameObject.GetComponent lt MeshRenderer gt ().material TNT Mat1 StartCoroutine(coroutine) else if (coll.gameObject.GetComponent lt MeshRenderer gt ().material.name "TNT 1 (Instance)") coll.gameObject.GetComponent lt MeshRenderer gt ().material TNT Mat2 StartCoroutine(coroutine) else if (coll.gameObject.GetComponent lt MeshRenderer gt ().material.name "TNT 2 (Instance)") coll.gameObject.transform.position Vector3.Lerp(coll.gameObject.transform.position, new Vector3(coll.gameObject.transform.position.x, 10,coll.gameObject.transform.position.z), tntFallTime) Destroy(coll.gameObject, 3) IEnumerator TNTFallDelay(int WaitTime) tntFall false yield return new WaitForSeconds(WaitTime) tntFall true This my code from Player script. If you look at my as you can see it's actually cubes holding together. All i want is When player touches one of the cubes For the first time it will change material When player touches that cube Second time it will change material again When player touches that cube Third time cube is going to fall down. But in these case (with my code) when i touch one of the cubes it does all of the if else statements in a second and cube falls down. |
0 | Character movement in Unity For an endless runner game such as Subway Surfer, in order to move your character so smoothly in both z axis and x axis, which component of the followings is better CharacterController or RigidBody? Can we use both of them together if so, will it have any effect on the performance of our game? |
0 | Raycast to the movement direction after hit a collider? I'm working on PingPong game style. My ball keep rotate on all direction. I want to use raycast to show me the direction ball will take after hit a wall or collider. Example public GameObject Ball public Rigidbody rg public float StartSpeed public bool StartGame false void Update() if (StartGame true) rg.AddForce(arrow.transform.right StartSpeed) var vel rg.velocity currentSpeed vel.magnitude if (currentSpeed gt StartSpeed) StartGame false RaycastHit hitB Ray fow new Ray(Ball.transform.position, Vector3.forward) if (Physics.Raycast(fow, out hitB, 200)) print(hitB.collider.name) Debug.DrawLine(fow.origin, hitB.point, Color.yellow) |
0 | Unity 5 C Scripting Switching Cameras How can I switch cameras from First Person to Third person or from thrid person to first person. Like at GTA V you can switch the cameras. How to do this? Tnx for your time. |
0 | Programmatically creating new tags in Unity I'm writing a custom editor script to add tags programmatically. I got the error of IndexOutOfRangeException Array index is out of range from the lines below SerializedObject tagManager new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings TagManager.asset") 0 ) SerializedProperty tagsProp tagManager.FindProperty("tags") These are my codes SerializedObject tagManager new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings TagManager.asset") 0 ) SerializedProperty tagsProp tagManager.FindProperty("tags") Adding a Tag string s "Instantiated" First check if it is not already present bool found false for (int i 0 i lt tagsProp.arraySize i ) SerializedProperty t tagsProp.GetArrayElementAtIndex(i) if (t.stringValue.Equals(s)) found true break if not found, add it if (!found) tagsProp.InsertArrayElementAtIndex(0) SerializedProperty n tagsProp.GetArrayElementAtIndex(0) n.stringValue s Latest Update Error IndexOutOfRangeException Array index is out of range is solved by resolving file location in my original script. I apologized for that. Fixed Added a line in the script to update the properties if (!found) tagsProp.InsertArrayElementAtIndex(0) SerializedProperty n tagsProp.GetArrayElementAtIndex(0) n.stringValue s tagManager.ApplyModifiedPropertiesWithoutUndo() |
0 | Timer breaks after changing scenes I am using this script below to move an animation in unity with no root motion. It simply walks across the terrain. I have timer attached also so the animation doesn't start to walk for 60 seconds. This works fine in the scene when played but when I navigate into this scene from another home scene the timer delay doesn't work as I guess it has been triggered already and has already reached the 60 second mark? I have tried using DontDestroyOnLoad but this just recreates the animation in the home scene also. I'm trying to keep the code as simple as possible and maybe add to the code below to fix it void Update () if (Time.time gt 60) transform.Translate (0, 0, Time.deltaTime) |
0 | Simulate shake, tilt and multi touch in Unity WebGl app I am developing a multi platform game in Unity. It works great on Android and also on WebGL (haven't yet checked iOS). My problem is that in some of the levels I need to use mobile specific actions like shake, tilt and multi touch. Is there any way to simulate this in a WebGL app? Examples of what I need Tilt to move an object without touching the object. The idea is to quot sail quot the object from the top of the screen into a basket at the bottom avoiding some obstacle on the way. Tilt to cause an object to move across the screen Shake to cause something to break. Multi touch to select two objects at the same time. |
0 | How can I write an additive mesh shader that splits the RGB channels while accounting for depth? I'm trying to create a sort of "hologram" effect. So far, what I have is an additive, three pass shader that uses ColorMask for each pass to separate the RGB channels. The problem is that doing so requires ZWrite to be off (first image) so that each pass doesn't intersect the others (second image). However, doing so means that the model geometry overlaps itself, which I don't want. I've tried the various methods of taking depth into consideration with transparency (This, for example) but they all cause problems when trying to separate the RGB channels. Is there some way to have each pass take depth into consideration within itself, but not with the other passes? |
0 | How manage multiple images in Unity? I'm new in Unity and creating a game. So I have a class PicManager in which I have to load my images(sprites) from assets into a List and then use them in my game. What is the proper way to load multiple images from a folder in Assets? I know, that I can use Sprite sprites Resources.LoadAll lt Sprite gt (texture.name) But this article of Unity says not to use Resource folder. |
0 | Unity How do I change the color of the "Screen" based on the Object's depth's (as a Screen Effect)? Yesterday I asked and solved my problem Unity How do I change the color of an object based on its depth? Today I tried to change the script(from yesterday) and apply it to the camera and it did not work. Every pixel which is printed on the Display has a depth (float), is that right? Based on that Depth I want every object to fade grey, relative to the screen distance to that "pixel". Is this possible? Or do I have to use that vertex fragment shader on every single Object and Plane and Sky and everything in the world? |
0 | Continous Movement and Gravity Switch With 1 button I have a sphere with a rigidbody on it, and it moves to the right continously as I need it, but as it moves I want the space bar to be able to switch the gravity (so it either rides on the ceiling or on the floor), as it moves along to the right. Please help, have been googling consistently for the past 3 hours. Here is the code I have so far public class movement MonoBehaviour public float movementSpeed 10 private bool haspressed void Start() void FixedUpdate() transform.Translate(Vector3.down movementSpeed Time.deltaTime) if (Input.GetKeyDown ("space") amp amp haspressed true) transform.Translate (Vector3.right movementSpeed Time.deltaTime) haspressed false else if (Input.GetKeyDown ("space") amp amp haspressed false) transform.Translate (Vector3.right movementSpeed Time.deltaTime) haspressed true Thank you sooo much! |
0 | How can I modify a static humanoid asset? I am new to Unity 3D. I bought an asset from the Unity Asset Store recently. It came in a "walking" stance. I was wondering if it was possible to modify this stance to become fully supine so can I modify the legs so that they are straight and next to each other? I am not sure if I can do this or not in Unity, or if I have to download Blender or Maya to do this. I have already tried forcing a stance change, through vertex snapping, but I am not having any luck with that. I have also tried editing the Character Joint settings, but I think that is if I wanted to animate the model, which I don't. This is what my character looks like currently I edited the character as per DMGregory's suggestion, but I am having trouble reimporting it back into my scene |
0 | Why does Facebook share callback return "success" if the user cancels? Unity Here is the code piece I used to debug public void Share (FacebookPost post) FacebookDelegate lt IShareResult gt innerCallback (result) gt foreach (var item in result.ResultDictionary) Debug.Log(item.Key " " item.Value) FB.ShareLink (post.linkURL, post.linkTitle, post.linkDescription, post.imageURL, innerCallback) The callback is expected to return a "cancelled" key if user closes the share dialog without sharing, but instead it returns "posted" key with "true" value, which is exactly the same result as when user literally "posts". And it returns no other data that can help me to decide if user actually shared or not. So, how can i decide if user shared or cancelled? |
0 | Handwriting or handwritten text recognition in augmented reality Is there any way available to detect handwriting of a user using augmented reality within Unity. Or convert user hand written text into characters? |
0 | Modifying an array of quaternions I have written the following function to inter change 2 specific elements of an array of quaternions private void ChangeRotations(Quaternion rotationsArray) Quaternion bone1Rot rotationsArray (int)Bone1ID Quaternion bone2Rot rotationsArray (int)Bone2ID Quaternion temp bone1Rot bone1Rot bone2Rot bone2Rot temp But when I use Debug.Log to see if this has taken effect, I realize that the 2 array elements are unchanged. What am I doing wrong here? |
0 | Issues with 3dsmax and Unity3d scale I changed the units in Blender so they are identical to Unity 3d. If I make a 1m 3 box in Blender, it will import into unity as exactly the same size as the standard cube. With 3ds max, I changed the unit setup to metric and made sure it was centimeters in the system unit setup tab. However, when I import an obj file made in Blender and used in Unity, it is absolutely tiny. I have to convert the model to meters on import and then, when exporting, I have to set the model scale to .01 otherwise it is enormous in the unity scene. I've tried changing the max units to meters and nothing changed. How do you change the max unit grid setup so one grid unit is 1m 2 and exactly equivalent to unity's grid? |
0 | Get the dropped object using IDropHandler.OnDrop In Canvas, I drag some UI objects to a panel using this code public void OnDrag(PointerEventData eventData) Vector3 screenPoint Input.mousePosition screenPoint.z 10.0f Item2Drag.position Camera.main.ScreenToWorldPoint(screenPoint) But what I can't figure out is when I dropped an object on the panel, how can I get the gameObject which has been dropped? |
0 | Why does OnControllerColliderHit not work while Physics.CheckSphere() does? Using the following code below, when my character hits a crate and goes over it, it ends up floating in the air, while jumping is no issue. That successfully lands on the ground. using UnityEngine public class Testing MonoBehaviour public CharacterController Controller speed of the character public float Speed 12f earth gravitational value public float Gravity 9.81f Vector3 velocity hit point of character float hp 90 bool Grounded true public void OnControllerColliderHit(ControllerColliderHit hit) Grounded true hp velocity.magnitude velocity.y 0 Debug.Log(hp) public void OnControllerColliderExit(ControllerColliderHit hit) Grounded false public void Checkstatus() if (Grounded false) velocity.y 0.5f Gravity Time.deltaTime void Update() float x Input.GetAxis( quot Horizontal quot ) float z Input.GetAxis( quot Vertical quot ) Vector3 move transform.right x transform.forward z Controller.Move(move Speed Time.deltaTime) if (Input.GetKeyDown(KeyCode.Space) amp amp velocity.y 0) velocity.y 12 Grounded false check if it grounded Checkstatus() Controller.Move(velocity Time.deltaTime) Here's an image showing the floating player And why does the code below (using Physics.CheckSphere()) have no issue? Feels like the above code is better (if working correctly), as it doesn't need to waste resource on checking the condition of Grounded (like in checkstate1()) every frame. using UnityEngine public class NewPlayerMovement MonoBehaviour public CharacterController Controller public float Speed 12f public float Gravity 9.81f Vector3 velocity public LayerMask groundmask float hp 90 bool Grounded true Update is called once per frame void checkstate1() Grounded Physics.CheckSphere(this.transform.position, 0.85f,groundmask) if (Grounded true) hp velocity.magnitude Debug.Log(hp) velocity.y 0 public void Checkstatus() if(Grounded false) velocity.y Gravity Time.deltaTime void Update() checkstate1() float x Input.GetAxis( quot Horizontal quot ) float z Input.GetAxis( quot Vertical quot ) Vector3 move transform.right x transform.forward z Controller.Move(move Speed Time.deltaTime) if (Input.GetKeyDown(KeyCode.Space) amp amp Grounded true) velocity.y 12 Grounded false Checkstatus() Controller.Move( velocity Time.deltaTime) |
0 | Refactoring out asynchronous webrequests to an interface I have a Unity project with UnityWebRequest calls in it. They are all working correctly, but I'd like to refactor them out (they are implemented pretty badly at the moment). The way I would like to do this is with a WebRequestSender class that implements an IWebRequest interface. Each call would return a WebResult object that I can use. public class WebResult public long ResponseCode get set public bool IsError get set public string Value get set public static WebResult Success(long responseCode, string value) return new WebResult IsError false, ResponseCode responseCode, Value value public static WebResult Failure(long responseCode) return new WebResult IsError true, ResponseCode responseCode, I'm having trouble understanding how to implement the interface, as these calls are asynchronous. Ideally, in the script when I need to make a call, I would have one line, like so WebRequest.Login(form) and that would return the result. I'm not sure what I have to add for it to wait for the call, or however it is executed. public interface IWebRequest WebResult Register(WWWForm form) Do I need to alter the return object so it allows for asynchronous calls? Or do I have to change the implementation the call of the implementation? As for my implementation, it doesn't work. The return statement on the Register function isn't called (even if it was, I'm not sure the return object would be populated?) Sample below public class WebRequestSender MonoBehaviour, IWebRequest private const string REGISTER URL "http localhost 51044 api Users Register" private WebResult webResult public WebResult Register(WWWForm form) StartCoroutine(MakeWebCall(REGISTER URL, form, (UnityWebRequest webRequest) gt RegisterDelegate(webRequest))) return webResult private void RegisterDelegate(UnityWebRequest webRequest) if (webRequest.isHttpError webRequest.isNetworkError) webResult WebResult.Failure(webRequest.responseCode) else webResult WebResult.Success(webRequest.responseCode, webRequest.downloadHandler.text) private IEnumerator MakeWebCall(string url, WWWForm form, Action lt UnityWebRequest gt finishDelegate) using (UnityWebRequest www UnityWebRequest.Post(url, form)) yield return www.SendWebRequest() finishDelegate(www) |
0 | Unity Animator not animating player, but following transitions perfectly in Animator Window I am trying to animate a model in my project, and although I have been successful doing the same in other projects, I am not succeeding in this one. The model does not seem to animate, although in the Animator window, everything looks fine, transitioning from one state to the other and going back. I have followed the tutorials to import animations from the site where I downloaded the animation, and each animation is the same as other working animations in other projects The animations play as expected in the inspector window. I have tried modifying the quot Apply Root Motion quot in my character and it does not work either way. My Player model has these properties And I have tried adding a Rigid Body but it didn't work neither. I have spend several hours trying to solve this issue and I am running out of ideas to try. How can I make the animation work as expected? Cheers! |
0 | main camera not covering whole screen in unity3d I have been using unity and i got a problem where my main camera is covering only the first half of the floor i made. camera position is left and the floor is rotated ,i m posting an image please help . I have shown a player white coloured and an enemy pink coloured .player is not shown as you can see. |
0 | I want camera to be positioned on the player also x axis should move continuosly by .05f in unity 2d I am creating an 2d platformer and I am newbie to Unity any help will be highly appreciated. I want the camera to be positioned on the player and also the X axis should move continuously by .05f. And if player is not moving or stuck somewhere and if player is behind camera player (because X axis is automatically moving by .05f) then player should die. Is it doable? I am using Cinemachine and any script logic will be appreciated. |
0 | "Occlusion culling data is out of date. Please rebake" No scene specified, Unity 5.6.2 I've inherited a Unity project with hundreds of scenes. When I try to build it for consoles mobile I get 11 errors saying "Occlusion culling data is out of date. Please rebake" and the build fails. Double clicking on these errors takes me nowhere, and no scenes are specified. It is my understanding that I can only bake occlusion culling by opening the scene manually and hitting the bake button. Due to the size of this project, that would take many hours. The game runs fine from within the editor, but simply won't export to consoles. How can I do any of the following Automatically rebuild all occlusion culling information. Find which scenes are out of date. Disable occlusion culling project wide, letting me at least get a build onto dev kits out for further evaluation. Thanks for any help at all. |
0 | Child transform's position not updated as parent moves I have a parent game object Object1. It has a child, which is simply an empty game object called ReferencePoint. ReferencePoint can be any arbitrary point on Object1 itself. I have another game object Object2. It has a public field called RotationReference, of type Transform. In the inspector, the ReferencePoint on Object1 is assigned to the RotationReference field on Object2. As Object1 moves, I expect ReferencePoint to change its position as well. Object2 is supposed to change its rotation to face its RotationReference in this case, the ReferencePoint on Object1 public override void Rotate() Vector3 relativeRotationReferencePosition this.RotationReference.position this.transform.position this.transform.rotation Quaternion.LookRotation(relativeRotationReferencePosition) However, I noticed that Object2 is not rotating at all, even when Object1 is moving. When I step through the call stack multiple times, I discover that this.RotationReference.position always has the same value, even though Object1 is moving. What am I missing here? |
0 | Is triangle count so much cheaper on hard surface models that on animated meshes? I have a human character that consists of 40k triangles. When I animated him, I noticed a huge impact on the frame rate. Then I created a 10k tris version of the same model and animated him, and the frame rate was significantly higher. I would like to ask if there is any formula or any other way to compare this situation with a high poly model of a hard surface model against a low poly version of a hard surface model. For example, I see some 3D model vendors that offer weapons for FPS games, and they call their weapons with 25k tris "lo poly". Am I missing something here? Is it really so cheap (for some reason that I haven't found out) to throw 25k of hard surface geometry to CPU or GPU, and it wouldn't make a noticable difference in comparision to a 3k tris hard surface model? I'm working with Unity and HDRP, if that is important for an estimation. Thank you. |
0 | Object not clamping after applying force impulse? I am having issue with clamping the vertical position of my character after applying force. This causes a jittery effect in my character. There are other several ways I think of, but I dont know if its the right way. Use translate, but ive read somewhere that if I am dealing with physics its better that to use addforce. Add an invisible gameobject with a collider to set bounderies. and third is clamp its movement while using addforce which in my case does not work. here is my code which I call on the update. rb player.GetComponent lt Rigidbody2D gt () Vector3 clampedPOS player.transform.position clampedPOS.y Mathf.Clamp(player.transform.position.y, 6f, 4f) player.transform.position clampedPOS rb.AddForce(Vector2.up upForce, ForceMode2D.Impulse) could someone help me with these? |
0 | Position orient parent to place child at a particular position orientation I have a GameObject for which I know its world position and rotation. From another app, I receive a new rotation and position, which should represent the local position and rotation of my GameObject. How can I compute the position and rotation of the parent object knowing the (world) position, the (world) rotation, the localPosition and the localRotation of its child? How can I find the necessary transform to obtain the second pair of coordinates from the first pair of coordinates? |
0 | Unity job system compatibility for end user? I'm thinking about using Job system. But it requires .Net 4.x (also look like .Net 4.x will be default for Unity in 2019). It is a little hassle for me cause I'm using Visual Studio 2015, I have to download amp install .Net target pack 4.7 My question is If my game is developed with .Net 4.7.2 (so that I can use Job system), does it require the end user installing .Net 4.7.2 to play the game? My target user is low end PC (they may using windows 7, I see that .NET Framework 3.5.1 is included in Windows 7) |
0 | Camera looking around with mouse Unity, C I am building a script in C for camera logic in Unity, the camera is supposed to follow the player (a 3rd person character) around and the user should be able to look around using the mouse, so far everything works fine (the following logic and looking around on the horizontal axis) the problem is I can't get the camera to move along the vertical axis, left and right are fine but up and down are not working. This is the C script public class PlayerFollow MonoBehaviour public Transform PlayerTransform private Vector3 cameraOffset Range(0.01f, 1.0f) public float SmoothFactor 0.5f public bool LookAtPlayer false public bool RotateAroundPlayer true public bool RotateMiddleMouseButton true public float RotationsSpeed 5.0f public float CameraPitchMin 1.5f public float CameraPitchMax 6.5f Use this for initialization void Start() cameraOffset transform.position PlayerTransform.position private bool IsRotateActive get if (!RotateAroundPlayer) return false if (!RotateMiddleMouseButton) return true if (RotateMiddleMouseButton amp amp Input.GetMouseButton(2)) return true return false LateUpdate is called after Update methods void LateUpdate() if (IsRotateActive) float h Input.GetAxis("Mouse X") RotationsSpeed float v Input.GetAxis("Mouse Y") RotationsSpeed Quaternion camTurnAngle Quaternion.AngleAxis(h, Vector3.up) Quaternion camTurnAngleY Quaternion.AngleAxis(v, Vector3.up) Vector3 newCameraOffset camTurnAngle camTurnAngleY cameraOffset Limit camera pitch if (newCameraOffset.y lt CameraPitchMin newCameraOffset.y gt CameraPitchMax) newCameraOffset camTurnAngle cameraOffset cameraOffset newCameraOffset Vector3 newPos PlayerTransform.position cameraOffset transform.position Vector3.Slerp(transform.position, newPos, SmoothFactor) if (LookAtPlayer RotateAroundPlayer) transform.LookAt(PlayerTransform) |
0 | Unity RectTransformUtility.ScreenPointToLocalPointInRectangle What does the unity's RectTransformUtility.ScreenPointToLocalPointInRectangle do I've read unity documentation but I didn't get the clear meaning. |
0 | How to make an object jump an equal height whenever it hits the ground? So, I want to make an object jump an equal height whenever it touches the ground. Something like a bouncing ball. But I can't use Physics Materials. Here are some ways that I tried Used Physics.CheckSphere isGrounded Physics.CheckSphere(rayPoint.position, grounDistance, groundLayer) if(isGrounded ) rb.AddForce(transform.up jumpForce, ForceMode.Impulse) Used Raycast bool groundHit Physics.Raycast(rayPoint.position, transform.up, rayDistance, groundLayer) if(groundHit) rb.AddForce(transform.up jumpForce, ForceMode.Impulse) In each cases, the object jumps a different amount of height each time it reaches the ground. How can I make it jump an equal height each time? |
0 | Unity How can I enlarge the sprite to avoid the movement of the character when the pivot change? Changing the pivot to custom on all of the sprites is not a viable option for me Video showing the problem https youtu.be YpAdamkbhFA |
0 | Object look at target direction? How to make an object look at the target direction not at the target himself ? public Transform target void Update() transform.LookAt(target) float step 2 Time.deltaTime transform.position Vector3.MoveTowards(transform.position, target.position, step) |
0 | Unable to destroy collider Unity3d So I was making an android game in unity3d. I wrote a script to draw straight lines with touch what I do is I first create a gameobject named temp and add line renderer to it and give the line renderer properties. Then I create a collider gameobject , parent it to the line and change its dimensions to the dimension of the line. What I am trying to do is add two colliders one while the line is being moved i.e "touch.phase TouchPhase.Moved" and delete this collider and add another collider when "touch.phase TouchPhase.Ended". For some weird reasons I am not able to delete the first collider. Here is my code void Update() foreach (Touch touch in Input.touches) if (touch.phase TouchPhase.Began) temp new GameObject() temp.AddComponent lt LineRenderer gt () temp.layer LayerMask.NameToLayer("lines") lr temp.GetComponent lt LineRenderer gt () lr.positionCount 2 lr.SetWidth(0.2f, 0.2f) lr.material new Material(Shader.Find("Sprites Default")) lr.SetColors(Color.black, Color.black) temp.transform.position camera.ScreenToWorldPoint(touch.position) camOffset fingerUp camera.ScreenToWorldPoint(touch.position) camOffset lr.useWorldSpace true spawnCollider false Detects Swipe while finger is still moving if (touch.phase TouchPhase.Moved) lr.SetPosition(0, fingerUp) fingerDown camera.ScreenToWorldPoint(touch.position) camOffset lr.SetPosition(1,fingerDown) spawnCollider true lastLine temp The first collider temporary one BoxCollider2D col1 new GameObject().AddComponent lt BoxCollider2D gt () col1.transform.parent temp.transform float lineLength Vector2.Distance(fingerUp, fingerDown) col1.size new Vector2(lineLength, 0.2f) Vector2 midPoint (fingerUp fingerDown) 2 col1.transform.position midPoint float angle (Mathf.Abs(fingerDown.y fingerUp.y) Mathf.Abs(fingerDown.x fingerUp.x)) if ((fingerUp.y lt fingerDown.y amp amp fingerUp.x gt fingerDown.x) (fingerDown.y lt fingerUp.y amp amp fingerDown.x gt fingerUp.x)) angle 1 angle Mathf.Rad2Deg Mathf.Atan(angle) col1.transform.Rotate(0, 0, angle) if (touch.phase TouchPhase.Ended) if (spawnCollider true) Destroy(col1) Deleting the first collider Adding the final collider BoxCollider2D col new GameObject("Collider").AddComponent lt BoxCollider2D gt () col.transform.parent temp.transform float lineLength Vector2.Distance(fingerUp, fingerDown) col.size new Vector2(lineLength, 0.2f) Vector2 midPoint (fingerUp fingerDown) 2 col.transform.position midPoint float angle (Mathf.Abs(fingerDown.y fingerUp.y) Mathf.Abs(fingerDown.x fingerUp.x)) if ((fingerUp.y lt fingerDown.y amp amp fingerUp.x gt fingerDown.x) (fingerDown.y lt fingerUp.y amp amp fingerDown.x gt fingerUp.x)) angle 1 angle Mathf.Rad2Deg Mathf.Atan(angle) col.transform.Rotate(0, 0, angle) I have added comments where I am doing what. |
0 | How to attach an UI button to a prefab and follow it in Unity2D My plan is creating a button above my prefab (a tree) and whenever my character is detected, the button will appear and allow me to click on it to active a dialog. I just want my trees are randomly spawned and stay still so it's not "follow" actually but I would like to know in that case too. I did some researches but most of them were about Text and HP MP things, which weren't used by UI system. One more thing, I kinda new to code so it would be fantastic if I got a full code (Button follow only). Thanks in advanced. |
0 | High poly vs Low Poly when creating model I am new in game development, but I have some knowledge in Maya and 3ds Max, I want to create pirate ship for game. So I spoke with many 3d artists and there are different opinions about low polygons and high polygons modelling. I am an iOS developer too so I know that it's hard for computer to process many polygons, so we should reduce amount of faces as much as we can. But my question is much more connected to 3D. Do I need to create low polygons model at start and then smooth it to increase amount of faces or do I need to create high polygons model and then reduce amount of edges, faces and etc? |
0 | UI Button OnClick not playing AudioClip on gameObject Basically, I am loading an Audio Clip onto a game object's Audio Source in the Awake function when the game starts. When I click on the game object a UI comes up that basically has a Play button attached and all I want to do is play the Audio Clip on the Audio Source. The problem is I can see that there is an Audio Clip on the Audio Source at runtime and I can play it in the inspector at runtime but, when I click the button nothing happens. I have tried just referencing the gameObject in the OnClick() of the UI button and that doesn't work and I have also tried going through and getting the gameObject through GameObject.Find public void PlayMe() GameObject objs GameObject.FindGameObjectsWithTag("Voice log") foreach (GameObject obj in objs) if (obj.layer LayerMask.NameToLayer("Selected")) Debug.Log("Found it") if (obj.GetComponent lt AudioSource gt ().clip.loadState AudioDataLoadState.Loaded) obj.GetComponent lt AudioSource gt ().Play() Debug.Log("Should Play") Both of my Debugs print when I click the Play button. |
0 | Identify whether object is off screen or not I have placed three game object in the scene.How to know whether the object is visible on the screen.Print a message if the object is not visible on the screen. |
0 | How do you make a Pong slider using touch events for mobiles? I am stuck with an issue of moving the slider on android mobiles with finger touch event while developing pong game in unity 3D, though its working fine for pc. This game is developed in 2D environment... please help me if anyone have available solution to this issue Actually I have developed this game for pc so I have code for the movement of slider accordingly as below var keyup KeyCode var keydown KeyCode var speed float 1 function Update () if(Input.GetKey(keyup)) rigidbody2D.velocity.y speed else if(Input.GetKey(keydown)) rigidbody2D.velocity.y speed 1 else rigidbody2D.velocity.y 0 But now i want to use this game for android mobiles. |
0 | How to make an enemy spawner that selects from a list of potential enemies? (Unity) I'm just making a practice version of a basic 2D RPG, but I'm trying to build a spawner kind of object that could be scaleable across the entire game. That is, there would be multiple types of enemies, and each instance of such a spawner would have a specific set of enemies that it would spawn. I'm sure the answer is very simple, but I'm at the beginning stages of all of this. I guess really I just want a simple list that I can attach to my object and add the enemy names to it so that it can draw from that to figure out what they would spawn. |
0 | How do I set the Jump distance and height of my sprite in C I have been able to make my sprite jump for a platformer I am making in unity. I can't seem to be able to make him jump a certain height or distance though, every time he jumps it's like he's jumping on the moon, any suggestions? Here's my code using UnityEngine using System.Collections public class playerScript MonoBehaviour public bool grounded true public float jumpPower 190 public float jumpSpeed 100f private bool hasJumped false Use this for initialization void Start () Update is called once per frame void Update () Do something if(!grounded amp amp GetComponent lt Rigidbody2D gt ().velocity.y 0) grounded true if (Input.GetKey(KeyCode.Space) amp amp grounded true) hasJumped true GetComponent lt Rigidbody2D gt ().AddForce(Vector3.up jumpSpeed) void FixedUpdate () if(hasJumped) GetComponent lt Rigidbody2D gt ().AddForce(transform.up jumpPower) grounded false hasJumped false Any help would be greatly appreciated ) |
0 | Legacy GUI run OnGUI only once I remember something about onGui being able to be run multiple times per frame, and I also seem to recall that you can check 'which state' the onGUI is being run in, so that you can do all of the intense logic in just the part that gets run once. Does anybody know what I am talking about I can't seem to remember what it was called and it is making googling it a daunting task. Thanks! |
0 | Mesh deformation maya to unity I have a model that has been modeled amp rigged in Maya, whenever i export it as an FBX and take it into unity it seems to collapse at certain areas (see the attachments for a before and after). The model is fine when brought into unity in the T position but once I give a pose in maya amp get it to unity it seems to collapse in certain areas. I ve even tried importing FBX file into 3ds max , model seems to have no problem in it. Its only when I import into unity I seem to get this problem. |
0 | Only do 1 SphereCastAll in Unity3D? I just want to make one SphereCastAll with a center and a radius. I don't want unnecessary sweeping in a desired direction with a desired length. How is this achievable? My solution is pretty unreliable, I think. var hits Physics.SphereCastAll(center, radius, forward, 0.0001f, mask) |
0 | How to continue Lego microgame tutorial? I was passing Lego microgame tutorial. I closed it and quit Unity. Now, how can I continue it from the same place? If I opening it's project, I am getting just silent Unity project, without any guidance. |
0 | How to work with a scene objects in batchmode? I had an object in first scene, with DontDestroyOnLoad parameter. And when the second scene (void Start ()) loaded, I searched for this object through GameObject.Find(). But this function works only in graphical mode. I can do this EditorSceneManager.OpenScene("Assets Scenes Main.unity") GameObject go GameObject.Find("TestObject") But this will not work, engine will be searching only static objects (wich were originally on this scene). Are there any options? Maybe I should use some additional parameters (I didnt find anything) |
0 | How to get a pixel color from a specific sprite on touch (unity)? I have a 2 layers of a different sprites. How can i get a pixel color from lower sprite? I know how to get touch and world coordinates, but i have no idea what to do next. Touch touch0 Input.GetTouch(0) screen touch coordinates Vector2 playerPick GetComponent lt Camera gt ().ScreenToWorldPoint(touch0.position) world coordinate |
0 | Can Unity4 and Unity5 projects coexist in the same computer? I've Unity5 installed (free edition). When I started with Unity3D I did with 5 and never had the 4 before. A friend has passed me legacy code of a 90 complete game he used to do with Unity4 as he no longer wants to dedicate to videogames, for me to use that to finish it. If I load that code into the Unity5, the "automatic upgrader" starts to do lots of changes. And finally the thing does not play. Says All compiler errors have to be fixed before you can enter playmode! The thing is he used some third party libraries, like the tk2droot among others and seems that the code of that and other dependant libreries is rather old, so I do not only need to scan over his code for the "v4 to v5 upgrade changes" but also I've to scan all his dependencies, which is rather a suicide at least for an initial contact like "let's just see if this compiles". Questions Is there any way make Unity5 "behave" as Unity4 so it does not do the code upgrade and it uses the old API? Ie Compile v4 code within v5 IDE? Alternatively, is is possible to freely install Unity4 parallel to Unity5 so they do not interact and I am able to compile his source un Unity4 while doing the new things in Unity5? The easiest solution I can find is to have 2 computers, one with Unity4 and the other with Unity5 but seems a but weird to me. I'm sure I'm not the only one with this problem. How do game developers with codebases in Unity4 and Unity5 make all the workflow? PD Focusing on Android now only. No need to publish for iOS, web, consoles, etc. Thanks. |
0 | How do you rotate the camera using right mouse clicks with Cinemachine? How can I rotate the camera around the player using right click? |
0 | Message Passing b w LAN Server Only and LAN Client on Different Scenes in Unity I want to pass message back and forth on client and server which are on different scenes, how can I do that in Unity? Following is my Scenario I have 5 scenes BaseScene (2) OfflineScene (3) OnlineScene (4) ClientOnline (5) ServerOnline. All these scenes have button having text of the names of the scenes. On Base Scene, I have add empty game object on which i have placed "customNetworkScript" which extends from "NetworkManager" script and also placed "Network Manager HUD" on it. Following is the code which i have placed in "customNetworkScript" public class customNetworkScript NetworkManager public override void OnClientSceneChanged(NetworkConnection conn) SceneManager.LoadScene("ClientOnline", LoadSceneMode.Single) ClientScene.Ready(conn) ClientScene.AddPlayer(conn, 0) public override void OnServerSceneChanged(string sceneName) SceneManager.LoadScene("ServerOnline", LoadSceneMode.Single) I have placed "OfflineScene" and "OnlineScene" in the fields, named "Offline Scene" and "Online Scene" in "Network Manager" component. Also have placed an empty prefab in "Spawn Info" in "customNetworkScript" and it has component "Network Identity" on it. Now when i run project, on one instance, I click on "LAN Server only" and on another instance, I click on "LAN Client". And I get my respective scenes on both the instances "ServerOnline" appear on instance where I click "LAN Server only" and "ClientOnline" appear on other instance. What I want is, when i click on "ServerOnline" button, a message string will pass on to "ClientOnline" scene and same happens in backward direction when i click on "ClientOnline" button. I have tried "Rpc" and "Command" but they only work when I click on "LAN Host" instead of "LAN Server Only". I have tried very hard but couldn't find anything useful. It will be a great pleasure if someone explain to me in detail along with the code, how can I achieve this. ThankYou Very Much for Your Time. |
0 | Remove previous scenes from memory in Unity 3d I'm making a game in unity3d which I optimized as much as I can. I've made different levels in each scene. After a few scenes the game starts to lag on mobile devices. And works smoothly if application is restarted and game is continued from last scene . How can I clear previously loaded scene in Unity3d or overcome the problem I mentioned above ? |
0 | Why do my NPC's fall through the world when I select them as triggers? I'm making a game in Unity where when the player comes into contact with an NPC it will switch scenes. I have the code for it and made sure all NPC's have rigidbody as well as using gravity and convex. They do not fall through the world but as soon as I click the trigger box on the mesh collider they start falling straight through the world. The switching scenes code works fine I tested it and it does switch the scene. |
0 | How to hide objects behind an invisible plane? I am using Unity 2019.1.4f1 (personal) in regular 3D mode. I want to make a material for a plane that will cause everything behind that plane to be invisible. I want a character who steps through a doorway to appear to disappear into "hammerspace" when he passes the door frame. I will post pictures in a minute. Blender concept (note how space after the doorframe is successfully occluded) Unity WIP (note how path after doorway is not yet occluded) |
0 | How to write properly shader with gradient based on vertex color? I took 4 squares with the outer corners painted in black, and the other ones in white. For some reason, they have a different gradient. fixed4 frag (v2f i) SV Target fixed4 mainTex tex2D( MainTex, i.uv) fixed4 overTex tex2D( OverTex, i.uv3) fixed4 final fixed4(lerp(mainTex.rgb, overTex.rgb, overTex.a) i.color, 1.0) final lerp(float4(0, 0, 0, 1.0), final, i.color.a) shadows return final How can i make the same gradients as bottom left and top right? In game this is faces of blocks (like minecraft) and gradients is smooth shadow light. So I cannot change tris |
0 | Unity Editor Adding Object Fields on button click So I am trying to make a button that will spawn an object field and a float field when clicked. Each object field being unique, so I can add gameobjects to it. I can t think of a way to do this. This is purely Editor Scripting. Also, if there is an option to delete a row (the object field and the FloatField) that would be amazing |
0 | Ensuring linear velocity remains constant even when turning I am using Ackermann steering to rotate a vehicle. The code is as follows if (turningLeft turningRight) Rotate around a dummy pivot point float turnDir turningLeft ? 1 1 Vector3 turningPivotPoint dummyPivot.transform.TransformPoint( new Vector3(turningCenterDistance turnDir, 0, 0)) dummyPivot.transform.RotateAround( turningPivotPoint, Vector3.up gasDir turnDir, angleVel Time.deltaTime) The player is pressing the gas if (isGas) angleVel Mathf.Lerp (angleVel, maxAngleVel,Time.deltaTime) if (angleVel 0) turningLeft turningRight false gasVel Mathf.Lerp(gasVel, angleVel Mathf.Deg2Rad turningCenterDistance, Time.deltaTime) dummyPivot.transform.position dummyPivot.transform.position dummyPivot.transform.forward Time.deltaTime gasVel gasDir The issue is that the speed of the vehicle when it is turning does not match its speed when driving straight. Driving the vehicle in circles will be slower than driving the vehicle forward. How do I fix this? |
0 | Unity Combining Passes in Shader I have a shader which uses multiple passes to determine the thickness of an object at each point. I want to use this thickness value in order to sample from a texture, which will determine the color of the screen at that point. However, since the calculation is performed in two passes, I don't have any way to access the one value which results at the end, which is what I would be using to index the uv for the texture. Thanks for any help in advance! Properties MainTex ("Texture", 2D) "white" SubShader Pass Cull Back ZWrite On ZTest Always CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct appdata float4 vertex POSITION float3 normal NORMAL struct v2f float2 depth DEPTH float4 vertex SV POSITION v2f vert (appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.depth UnityObjectToViewPos(v.vertex).z 200 ProjectionParams.w return o sampler2D MainTex fixed4 frag (v2f i) SV Target float c 1 i.depth fixed4 col fixed4(c,c,c,1) return col ENDCG Pass Cull Front ZWrite On ZTest Always BlendOp RevSub Blend One One CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct appdata float4 vertex POSITION struct v2f float2 depth DEPTH float4 vertex SV POSITION v2f vert (appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.depth UnityObjectToViewPos(v.vertex).z 200 ProjectionParams.w return o sampler2D MainTex fixed4 frag (v2f i) SV Target float c 1 i.depth fixed4 col tex2D( MainTex,c.xx) fixed4 col fixed4(c,c,c,1) return col ENDCG |
0 | Persistent variable for all list members inside a loop called every frame I'm trying to add a sort of manager to handle all objects in a list and increase a float value that each individual member of the list has given a condition every single frame. I'm having some trouble wrapping my head around the actual code I need though. So say I've got an OverlapCircleAll or trigger checking for tagged objects in a certain radius. These objects are then added to a List (foo). Then, I go through foo with a for loop and declare a float value x for each object. What I need is for each object's x to increase when the object is also on another list, bar. So something like this for (int i 0 i lt foo.Count i ) float x or float x 0 ? if (bar.Contains(foo i )) x 1f The problem is, I can't figure out how to make the value of x persist each loop. This function is called in Update() so the idea is that the longer an object is in both foo and bar, the higher its value of x is. I don't know how to save the value of x for the next loop though. Ideally something like for (int i 0 i lt foo.Count i ) float x if (lastX ! null) x lastX else x 0 if (bar.Contains(foo i )) x 1f float lastX x But I don't know a) how to save lastX for each object in the list and b) set x to lastX (because for each loop it creates a lastX). I thought about storing each x in an array of floats and calling the corresponding array i to foo i to get x, but if I remove something from the list then the array will become desynchronised with the list and all the x values will get muddled up. What is the correct way to go about this? |
0 | Force change prefab source I have a prefab A and i use it in scene A (as gameobject A). Then i to save that scene A as scene B and also renamed the gameobject A to gameobject B. Then inside unity (in project window ) , i duplicated the prefab asset A to prefab B. Fyi, i'm using .blend (blender file) as the prefabs. in scene B, i want the gameobject B which refers to prefab A , to switch its prefab's source to prefab B. This way , i have 2 different scenes which has independent gameobjects which refer to unique prefab. So i can modify prefab A and will affect scene A but not scene B. Ussually, i can drag the gameobject to project window and choose create 'new original prefab' option, but this method can't be used, since i want both prefab as .blend file (so i can modify them directly using blender). What i did so far, is to drag prefab B to scene B, which then i have to manually redo all the setting which has been done in scene A . I want to avoid this tedious process. Does anyone have any idea ? |
0 | What does vertex disp and tessellate tessEdge mean? Shader Unity I came across the following declaration on unity tutorial pragma surface surf BlinnPhong addshadow fullforwardshadows vertex disp tessellate tessEdge nolightmap I think disp is the displacement shader but what does vertex disp mean? Likewise for tesselate tessEdge. from https docs.unity3d.com Manual SL SurfaceShaderTessellation.html Thanks. I am rather new to HLSL. |
0 | Manual response when 2 shapes made of rectangular volumes collide I have 2 compound objects made of rectangular blocks. One of them (the one that is moving) has a script that listens to OnTrigger callbacks. What I need is to position the moving compound object on the first compound object to make then not collide but stay in contact. As an example you can thing of two "spheres" made of blocks. Both spheres are on the floor. Then I move one of the spheres (still on the floor) and I detect that it collides the other sphere, so, I need to push the moving sphere up to make it not collide with the first one but stay in contact. I have a manual algorithm that make tests on the different blocks of the two groups to push it up enough to make them not collide but it is a bit intensive. Do anybody know if unity physic engine can help here? The main problem is that after I receive the collision I can not move the moving sphere up and recheck manually first of all because there's no Check for rectangles and on the other hand if I want to be notified by the physical engine after I move the moving sphere up (to see if it still collides)I need to wait a new frame which is not feasible in my case. P.S. I'm using unity engine. |
0 | problems getting a new position vector3 could someone explain to me why i can't get a new position that is outside the update method. if i set what's inside the void callposic to a Start I can't get any position, only if it's inside the update what can you do, because I don't want to use them in the update board. https www.youtube.com watch?v aNzJ5GUYAOA amp feature youtu.be public int index public Vector3 posic void Start() prev.onClick.AddListener(() gt void1( 1)) next.onClick.AddListener(() gt void1(1)) index 0 void Update() callposic() void callposic() transform.localPosition posic index void void1(int value) index index value |
0 | Unity pixel art distorted sprites I have a problem rendering my pixel art sprites properly in Unity. So far I have one character in a sprite sheet I made, with frames of size 64x64. The actual sprite is roughly 32x32 but I left room for movement in animations. I import the sheet following pixel perfection procedures I found on the internet using these settings As for the orthographic camera I set its size using this formula orthoCameraSize screenHeight (2 32) If I zoom on the sprite in scene it looks fine but when in game it gets rendered quite poorly (in game in scene pics below) What could be the source of the problem? I applied every good practice advice I could find on the web... Thanks for your help!!!! |
0 | The tile cursor is not on the same tile I selected Here is the image, when I select the tile I want to paint, it paints in the correct box where I want it to be but the white cursor should also be in the same box but it is 2 units to the left? This really makes it difficult to paint the tiles. I'm a beginner in unity and can't seem to fix this problem ( Thank you for your help! |
0 | Could a Peer To Peer network architecture be good for my fighting game I am looking forward to developing a 2D spaceship fighting, brawler game and I have so many ideas about it. I am going to make a single player component anyway, but the core of this game would certainly be its multiplayer. For this game, I was inspired by Brawlhalla and its dynamic play style. In my game, there has to be real time action features such as attack, dodge, getting hit, killed, so a reliable networking needs to exist. I have thought initially about a client server architecture, but a peer to peer connection would be in my opinion more easily for me to implement. I have read this article and it proves encouraging for me to go on with this simulation solution. Let me describe my concept A client initializes a room and using sockets, IP, port and the other players would after connect to him. Therefore, there is always a Master Client that handles the new connections and gives signal to other clients about a new existing player. Then, as the game is running, the byte data packets would stream each player's input, his position, his ship rotation, his ship status and so on, so that each of the other clients could run a perfect simulation of the initial client. In other words, this data packets would trigger all the actions on each client. As network protocol, I am thinking about TCP IP and should someone be willing explain to me in more practical terms the difference between this and UDP, I would be thankful. I have even computed how much data it would take to transmit over a second assuming a byte 256 array that holds all the data at one time multiplied by the number of calls per second (about 32 times) multiplied by the number of clients the data should be broadcasted to (3 4) results in about 32 kb s. It might be a dummy result, i might have left a lot of things out, but again, I am ready to learn. As a note, I do not intend to make at this moment a professional multiplayer system, but rather, I would like to learn more about this programming part of applications and I think this is a very good project idea to enhance my skills. Of course, I am opened to any advanced tips, solutions, materials and should I add anything else about my concept, please let me know. How is my theoretical model so far? |
0 | Unity pattern for multiple game views What are some proven and preferable patterns to realise multiple "screens" in the game? Not in the sense of displays (monitors) but "views" within the application. Say it's a Civ Heroes type game. We will typically have these screens during the proper gameplay Main map (strategic) Battle map (tactical) City management screen Research screen etc. As you can see, some of them are UI like in nature but some are full blown interactive scenes. We need to be able to Quickly switch between them Keep a global game state between them (e.g. the (in )famous GameManager instance must stay intact) Bonus points if able to make a fancy transition (e.g. city screen rolling down from above) Bonus points if able to keep one screen (e.g. city screen) only partly covering another (e.g. the strategic map) and both are animated Theoretical solutions I can imagine (I'm still a Unity noob) Separate scenes for each screen. But will the engine be able to switch between them fast? (I read that a scene is akin to a "level" in a traditional game, which usually means a loading time?) Also, how will I track the global state (GameManager)? Can I overlay one screen over another? Everything in one Unity scene but multiple cameras looking at different objects, with switching between them or nesting. E.g. one camera looking at the map grid, another at a city screen etc. But then I run the risk of objects from one "scene" (only virtually) affecting others (e.g. lights or particles) unless I place them sufficiently far apart. Is any of my ideas going in the right direction? Is there a better pattern that I'm missing? |
0 | Is it normal for the baking timer in Unity to increase? I'm having an unusual reaction from trying to bake my scene for Occlusion Culling (the scene was starting to lag and I thought this would optimize it) and I wanted to ask for advice. What's happening This scene and the previous scene are very similar in structure and appearance, only one scene has 2 large models in it. I selected every model object in the scene that wasn't a character, or had any animation, set it to static, then clicked 'bake' (according to the tutorial I was following and the previous being very successful) and this is where it starts going wrong. In the previous scene, beside Auto Generate Lighting On is a loading bar, which had 126 Jobs Remaining and took about an hour and a half to do (I was watching a show and each was 30 minutes long, I saw 3 before it completed) but this time, it showed Baking... ETA 10 26 20 And when it first started, it had 9 hours instead, then spiked up to 11 after 30 minutes. I'm not sure why there's such a dramatic difference between the two and with my very limited experience on this, I wanted to ask for advice from more experienced Devs. edit This is a screenshots of everything that appears in the static dropdown menu |
0 | Unity both duration and cooldown system I have a boss with machine gun and i am trying to make him shoot for 5 seconds and then stop for 5 seconds and so on. I tried to create an IEnumerator and call it on Start (as far as i know i can not call it from update) but its not the behaviour i want as i always want him to start shooting when he spots the player. Any help is appreciated. IEnumerator MachineGunShootTimer() while(true) machineGunOnCooldown false yield return new WaitForSeconds(3f) machineGunOnCooldown true yield return new WaitForSeconds(3f) |
0 | Does Animator.SetBool take precedence over Animator.SetTrigger in Unity's Animator? I've got an Animator with transitions from Idle to Walk or Dash. Walk requires isGrounded to be true and a float MoveX to be greater than .2. The Dash animation requires Dash trigger is returned. In my code, when the shift key is pressed I call anim.SetTrigger("Dash"), if a Walk key is pressed, I set anim.SetBool("Idle") to false and begin increasing MoveX. The problem I'm noticing is that when I play, and hit the dash button, it first starts walking and then after playing that animation it will then perform the dash animation. Looking in the animator as this is happening, it's clear that the walk animation plays in full before moving to the dash animation. What can I do to give priority to the Dash animation when that button is pressed? |
0 | Centre of mass not recalculated after scaling I am spawning a prefab object at runtime (actually, in the Start() method of another object), and I need to apply a scaling to the object. I made a little component to handle this public class Spawner MonoBehaviour public Transform SpawnPrefab public Vector3 Scale void Start () var spawn Instantiate(SpawnPrefab, Vector3.zero, Quaternion.identity) spawn.localScale Vector3.Scale(spawn.localScale, Scale) spawn.GetComponent lt Rigidbody gt ().ResetCenterOfMass() Has no effect The pivot point of the prefab I am spawning does not coincide with the centre of mass of the object. Therefore, the rescaling means that the centre of mass location relative to the pivot will change. However, it's not being updated automatically, so my spawned object has unexpected physics. I tried adding a call to GetComponent lt Rigidbody gt ().ResetCenterOfMass() immediately after the call to Scale() (the commented out line above), but this has no effect. However, if I put the call to ResetCenterOfMass() in the Start() method of a separate little component added to the spawned object, e.g. public class COMReset MonoBehaviour void Start() GetComponent lt Rigidbody gt ().ResetCenterOfMass() this does cause the centre of mass to be recalculated correctly. However, the spawned object appears to have already been through at least one physics update with the wrong COM by this time, and so has already acquired some unexpected momentum. Why isn't the COM being automatically recalculated, without me having to call ResetCenterOfMass() explicitly? And if I must trigger it manually, can I do that immediately after the calls to Instantiate() and Scale(), rather than deferring like this? |
0 | How to import character package in Unity I recently made a game in Unity 3D and I tried to import the FPS Controller package as the tutorial I was following said, but when I clicked Assets Import Package the only thing I saw was a button saying 'Custom Package' How do I get the character option when I click 'Import Package'? |
0 | Switch Vector 3 x,y,z Components Based on Rotation I have a cube that moves by rotating on its edge. I want my code to also work for cuboids. The following code is what I'm using to rotate my cube turnPoint transform.position new Vector3(0.5f direction x, 0.5f, 0.5f direction z) Location of edge (resets every 90 degrees) transform.RotateAround(turnPoint, axis, rotateSpeed direction) Turn around the edge It works fine, however I want to get this to work when the cube is scaled to be a cuboid. I tried multiplying the new Vector3's x, y and z components by the objects respective x, y and z scale. This works, but only for the first rotation. Is there a way this could work for all future rotations without using if else for all 4 rotations? |
0 | How can the player select his weapon among many? I'm working on the prototype of my game, I want one of the options to have a very large amount of weapons. I have searched for tutorials, but I have only found weapons changes where the weapons have already been loaded in the scene from the inspector, like this https youtu.be Dn BUIVdAPg where they are only activated and deactivated. But I want a game like dofus where there are hundreds of weapons, I think I have a data file of the weapons and so, I can load the correct model of the weapon. How can I get the model loaded? I have read other tutorials regarding the AssetBundle, but I think that is when you need to download the models from a server for example, but I just want to load them from the same project. sorry for the bad english |