_id
int64
0
49
text
stringlengths
71
4.19k
0
How can I parse different types of objects from JSON? I'm trying to save the player's inventory as a JSON data but I'm having a problem. I have a class Sword which extends an abstract class Weapon which extends another abstract class called Item. This is what JSON file looks like with the Sword and Armor objects in it "category" "type" "Weapon", "subtype" "Sword" , "id" 0, "value" 1, "name" "Wooden Sword", "description" "Sword made out of wood", "slug" "wooden sword", "stats" "wear" 100, "damage" 5 , "category" "type" "Armor", "subtype" "Helmet" , "id" 1337, "value" 1, "name" "Steel Helmet", "description" "Whatever...", "slug" "steel helmet", "stats" "wear" 100, "defence" 5, "vitality" 3, "dexterity" 1 How can I parse these objects into their respective C objects, putting the first entry into a Sword object and the second one into a Helmet object. There will be other types of objects in there too, so it's not limited on these two.
0
Children of canvas objects do not register OnMouseUpAsButton Objects I create inside my canvas do not register the OnMouseUpAsButton() event. I tried doing it on an empty project and it doesn't work so I guess I'm misunderstanding how something works. That being said, objects inside game world register event properly. I tried reading documentation but I still don't get why this is happening. My code (the only code used in the project) using UnityEngine using System.Collections public class test click MonoBehaviour void OnMouseUpAsButton() Debug.Log("Mouse up test click") public void Thisworks() Debug.Log("yes") void Start () void Update () My project objects I have spent the last 12 work hours searching for causes of this problem so I'm sure it is something absolutely obvious yet I just can't see it.
0
"The Object you want to Instantiate is null" But it works, can I ignore the error? This has never happened to me so I'm a bit confused. GameObject someObject Instantiate (Resources.Load ("Prefabs Items " someName)) as GameObject This throws an error but the object is actually instantiated and everything works as intended. The error doesn't stop the program no matter how many times I reproduce this. Can I ignore this error or is there some problem that I'm not seeing?
0
How to build only specified assets into assetbundle in unity I have searched through the few results pertaining to this particular question, but haven't found any results that work. A simple rundown of what i am looking for is to be able to make a single asset bundle of specified assets in order to be able to make an automated process for what the mod system i am making for the project i am working on. there are two ways I can think of that would be able to do this build specified resources and assets into an assetbundle build everything in a specified folder into an asset bundle all of what i have been able to find regarding this either wouldn't allow me to make the automated process i need or builds the all of the assetbundles and they have to be defined manually before hand. Any resources or suggestions to this issue would be greatly appreciated.
0
Can I have a fixed angle sprite with a non fixed angle CircleCollider2D? In Unity2D, can I have a fixed angle sprite with a non fixed angle CircleCollider2D? I would like to move my character using the circle physics (without fixed angle), but display him always as if he wasn't rotated (as if he had fixed angle). I thought I could just let the collider rotate, and then rotate back the sprite in the LateUpdate, however since the collider's center isn't 0,0, it "rotates sideway" and doesn't end up in the "original" position. My knowledge on matrices and quaterions is null, and trigonometry is only slightly above zero, so I'm a bit at a loss... how can I achieve the desired effect? In order to prevent a X Y problem, I want to do that since with box colliders sometimes the characters got stuck if a platform had even just 1 pixel step, the character couldn't walk over it. Also, slopes were a big problem. Changing the collider to a Circle was the obvious consequence I also tried to detect and add a small vertical speed but it didn't work very well and was becoming a mess.
0
How to calculate Camera correct position and distance to Frame all my Scene? Consider I have N dynamic points on my Scene, I would like to "frame" all them, with my Camera. How can i calculate (at runtime) Vector3 Position to correctly frame all my scene ? This is my idea Calculate Avarage for all my points Move my Camera "up" Zoom out to correctly "frame" all my points (i don't know how to calculate ) Use Unity LookAt(myAvaragePoint) I think i've to use some trigonometryc function to calculate the Y Camera position (to zoom in, zoom out), but i don't know which! Thanks
0
Unity Physics.Raycast give false positive while using layer mask I'm very new to Unity so please excuse my question if this sounds very basic to you. I'm following various tutorials and I have a small question regarding Physics.Raycast if (Input.GetButton("Fire1")) check ground hit first RaycastHit hit if (Physics.Raycast(ray, out hit, LayerMask.GetMask("Ground"))) Debug.Log(" PlayerMotion Hit" hit.collider.name " " hit.point) agent.SetDestination(hit.point) Here, even tough I expressively set the layer mask to "Ground", I still get a hit with the Player game object itself (the ground hit is working fine). I thought ok maybe I put the "Ground" layer as well on the player by mistake but I checked several times and it's not the case. I'm attaching a gif so you can see what's the issue exactly There's an easy by checking the collider.name but I still find it odd that the Raycast gives me a false positive with the player hit. Any idea what's going on ?
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
Change Text Inside A button, inside a Canvas, inside a GameObject Access all the texts inside of hierchy? .... Gameobject tile int count 1f float posX 0 float posY 0 .... GameObject blueTile (GameObject)Instantiate(Resources.Load("block blue")) tile (GameObject)Instantiate(blueTile, transform) for loop ... ... tile.GetComponent().GetComponentInChildren().text count.ToString() tile.transform.position new Vector2((float)posX, (float)posY) count As you can see by the image. My line of thinking goes like this I used to create Flash AS3 Applications and Games. I have used a number of API's and they usually have a lot in common. Unity, however, is very different and I may have not grasped the key concepts. I want to access my PreFab, named in Assets Resources (the root path) "block blue" All I wan to do is set up a row and columns of a box with a number inside of it. Before you go and ask, why the complicated mix of Objects? Well, Adobe had MovieClip and use of layers and also use of a timeline. Unity doesn't seem to have this in setting up a Scene (the Stage in Flash). So, I set up a block that looks like this (right of main image 66) It's a Canvas, to hold a Button, the button has a text. To move the Canvas, I put the Canvas inside a GameObject. This, to me, is like a MovieClip in Flash API. GameObject ButtonLight, Button TextBlack, Text I need to access TextBlack and also Text. Pretty easy right? I've been at this for 4 days, many many hours. EDIT It seems that it is working, somewhat. Looking at the reference photo and the Hierarchy reference, it looks like the blackText behind the blueText is changing as expected. But I cannot access the top BlueText. The Blue Text is also a child of type Text, but it's a second (layer?) copy of the text inside of the Button. So, it's getting the first Child Text, but how to access the second Text?
0
Unity XR Spectator Camera I would like to have a VR camera (for the player) but also have another camera (spectator). I am using Unity 2019.4.8f1 on the Universal Render Pipeline I have only been able to find outdated articles https blogs.unity3d.com 2017 12 12 spectating vr https unity3d.college 2017 05 08 unity3d spectator mode vr https forum.unity.com threads using a second cam while still rendering the vr camera for the vr headset.659434 Thanks!
0
How can I integrate someone well into my project? I am working alone, since over one year on a decent sized project... to speed up things i wanted to incorporate some friends into development, unfortunately i never did something like this before and so i dont know where to start. What is important to work as a team ? What should he know, see and understand ? And what shouldnt he be aware of ? And most important, how would you integrate someone into your project ?
0
Unity2D Isometric layering I'm developing an Isometric Game but I have problem apply the right layer for make, for example, a wall behind or in front of the Player depending on the Player position. I'm able of getting works in an orthogonal map relating the y axis value of an object with his layer but in an isometric map, the y axis is not aligned with the editor one. Anyone can help me understand how to manage this?
0
Render Occluded pixels to gray color In 3d space, objects can be occluded by another objects. By depth testing, the occluded faces are skipped rendering. Only the nearest(smallest) depth value pixels are drawn. But, sometime we need to render the occluded object or pixels for game play. To differentiate the occluded object's pixels from foreground pixels, some game use gray color to render the pixels. This is the sample images for the case. I guess this can be achieved by some sort of shader. How can I make this effects in Unity 3D Engine? Any hints or idea plz.
0
Is there a wall building tool in unity3d? I'm currently building a maze game in unity 3d and after building a few levels by placing and repositioning cubes by hand as walls, I think, that it would be nice if there was a tool to place walls, which are cubes with constant height and width, but have different length and rotations on the y axis, by joints you click to place a joint, and a wall goes in straight lines beetwen joints. So is there a tool like that?
0
How to enable and disable scripts on a Game Object? This worked briefly yesterday, I believe I did something to mess this up. All my inputs that I put in are correct therefor, it must be the code. I want to switch players. While the red cube's script is enabled and can move under the movement script I want the blue cubes movement script to be disabled and vice versus. Can you give me some insight into what I'm doing wrong? Please and thank you!! using UnityEngine using System.Collections public class PlayerMovementScript MonoBehaviour public float speed 2f public float height 2f public Component playerMovement public GameObject redCube public GameObject blueCube void Start() var bc blueCube.GetComponent lt PlayerMovementScript gt () bc.enabled !bc.enabled Update is called once per frame void Update () if (Input.GetButton ("Right")) transform.Translate(Vector3.right speed Time.deltaTime) if (Input.GetButton ("Left")) transform.Translate(Vector3.left speed Time.deltaTime) if (Input.GetButton ("Jump")) transform.Translate(Vector3.up height Time.deltaTime) var bc blueCube.GetComponent lt PlayerMovementScript gt () var rc redCube.GetComponent lt PlayerMovementScript gt () if (Input.GetButton ("Switch")) bc.enabled !bc.isActiveAndEnabled rc.enabled !rc.enabled
0
Rotate bone on 1 axis to look at another object Unity 3D I'm new to game development and I'm trying to create a basic 3D Tower Defence game as my first project. I've created a basic turret in Blender and I'm now trying to rotate 2 different bones to make the turret follow the enemy. The first bone (which I have working) rotates the turret to face the direction of the enemy. The second which I can't get right needs to rotate the gun at the top of the turret to look down at the enemy. I need it to keep facing the same direction as the rest of the turret and don't want it to tilt to either side. So it needs to move on 1 axis only. I have tried various things, including examples from the Internet but I can't figure it out. So far I've managed to get it to look down at its base, up at the sky and spin like a wheel. Basically everything except where it's supposed to be looking. Here is the code I have at the moment if (enemiesInRange.Count gt 0) Rotate Platform This section works fine Transform platform transform.root.Find("Armature BaseBone PlatformBone") Quaternion targetRotation Final rotation (I.e. facing the enemy) Vector3 turretPosition platform.position Store the turrets current position turretPosition.y 0 0 the Y axis to stop the turret tilting up or down Vector3 targetPosition enemyManager.activeEnemies enemiesInRange 0 .transform.position targetRotation Quaternion.LookRotation(targetPosition turretPosition) float rotateSpeed 2.0f Time.deltaTime platform.transform.rotation Quaternion.Lerp(platform.transform.rotation, targetRotation, rotateSpeed) Rotate GunBox TO DO This part is not working Transform gunBox transform.root.FindChild("Armature BaseBone PlatformBone LowerArmBone UpperArmBone GunBoxBone") Vector3 gunBoxPosition gunBox.position float angle Vector3.Angle(gunBoxPosition, targetPosition) gunBox.RotateAround(gunBox.position, Vector3.left, angle) Debug.Log(angle) Here's a picture of the turret to give you an idea what I'm working with. You can see in the screenshot that the bone's default X rotation is roughly 50. Enemies walk through the trench around the turret. The PlatformBone rotates everything from the silver platform upwards. I also don't understand why the line below makes the turret rotate instead of tilting it. I would expect to rotate the turret around the Y axis to keep it flat on the floor and face another direction. Yet I seem to have to do the opposite (If I select the PlatformBone its Y axis is facing up as expected) turretPosition.y 0 0 the Y axis to stop the turret tilting up or down
0
How to load and unload objects at a certain radius from the player? I am making a procedurally generated space exploration game in unity. I'm currently generating 5000 stars in a cube of a fixed size. Each star just gets a random 3d coordinate. What I would like to do is to dynamically load and unload stars at a certain radius from the player. This would be the maximum view distance. The algorithm that does this must be working with a seed for the universe, as the stars need to be loaded in the same spot when you revisit them. My idea is something like in the amazing Space Engine. I have pretty much no knowledge of algorithms that can do this, so I ask for your help.
0
Unity Trying to add an in scene 'press E to open' tag as UI element In Unity 5.4.1 I'm trying to add a tag that says 'press E to open' to a door as you approach it. I've got a RayCast pointing forward from the player, detecting the door and , connected to my PlayerController, I've got a copy of a prefab GameObject which itself contains a Text UI element. The GameObject interactionTag is instantiated into the scene when the player is close enough. But I'm having some trouble getting it to display correctly in the scene and I'm not sure why. Here are the relevant parts of my PlayerController public class PlayerController MonoBehaviour public Canvas canvas private Vector3 fwd private RaycastHit hit public GameObject interactiveTag private GameObject interactiveGameObject null private GameObject interactionTag void Update () fwd transform.TransformDirection(Vector3.forward) if (Physics.Raycast(transform.position, fwd, out hit, 3)) if ( hit.distance lt 1) interactiveGameObject hit.collider.gameObject GameObject interactionTag (GameObject) Instantiate(interactiveTag, interactiveGameObject.transform.position, interactiveGameObject.transform.rotation) interactionTag.GetComponentInChildren lt Text gt ().text interactiveGameObject.GetComponent lt IsInteractive gt ().interactionText this gets a text string from the door 'press E to open' interactionTag.transform.SetParent( canvas.transform, false) In game, the interactionTag is appearing though it's backwards and does not appear attached to the door. Also is any of this the best way of getting the 'press E to open' tag to appear attached to the center of the door? I'm beginning to wonder if what I'm doing is best practise. Thanks for any help.
0
How best to detect device performance capabilities and set quality setting accordingly when using Unity I am developing a Mobile game for Android and iOS on Unity. Currently Im in the optimisation stage of development and trying to work out what is the best way to detect device capabilities, with the aim of then setting an appropriate quality setting. OS platform detection is simple, but how can I detect between a high performance android device and a low or medium performance device at runtime? I did find this question that is similar https stackoverflow.com q 21565468 4148676 but the question is old, the answers not great and hoping there's a better way in the last 4 years of solving the problem. The only other solution I have is monitor the average FPS and adjust the quality based on the frame rate. Any advice would be appreciated.
0
How do I rotate an object back and forth? I want my object to rotate between two angles in relation to speed and it doesn't need to be a smooth rotation, how can I achieve that? Thank you in advance.
0
Drag and Flick Objects to any position (Unity3D) In unity, I have several boxes in one cluster. I want the user to be able to move any of these boxes to any position that they desire in the app, and have it stay there until they move it again. Also, I want the user to be able to flick any boxes and when it is flicked, have it bounce around the screen, as if it were trapped inside of the phone (but never leaving it). Any way I can do this? (This will be used for an Android Experiment)
0
Will using one class per inventory item create issue on the long term? I finally managed to plug my menu to my inventory system, display current items, use them etc. But the way I did it... makes me feel dirty. To cut short, my items are described this way using System public abstract class Item public abstract string Name get public abstract string Description get public virtual bool IsUsable get return false public virtual bool IsEquippable get return false public virtual bool NeedTarget get return false public virtual void OnUse() public class Potion Item public override string Name get return "Potion" public override string Description get return "Restores 100HP to one character" public override bool IsUsable get return true public override bool NeedTarget get return true public void OnUse(PlayerCharacter target) Effects.HealTarget(target, 100) public override void OnUse() OnUse(GameData.getFirstPc()) public class Poison Item public override string Name get return "Poison" public override string Description get return "Deals 100HP damage to one character" public override bool IsUsable get return true public override bool NeedTarget get return true public void OnUse(PlayerCharacter target) Effects.DamageTarget(target, 50) public override void OnUse() OnUse(GameData.getFirstPc()) My Inventory is declared like this public class Inventory private static Dictionary lt string, Item gt ItemDB new Dictionary lt string, Item gt () "00001", new Potion() , "00002", new Poison() , "00003", new HiPotion() , "00004", new FangOfDestroyer() , "00005", new Elixir() public static Dictionary lt string, int gt CarriedInventory new Dictionary lt string, int gt () When I want to add items to CarriedInventory I basically call CarriedInventory itemID newAmount Everything only uses the ID, and when I want to get an item's name I call ItemDB itemID .Name, when I want to use an item I call ItemDB itemID .OnUse() , etc My reasons for doing this were I can be as specific as I want on item uses as I want, I can have unique item effects without having to worry about extending it to all other items I can use the effects in the Effects class for general effects (heal, damage, etc) if later on I realize I need a new property for an item, I can just add a virtual property as default to the Item class (e.g. I realize I want an item to not be droppable, I add a public virtual bool IsDroppable with a value of true, and non droppable items can override this I avoid inheritance hell And... it works, it works, but it feels wrong. Is it wrong? How wrong? Is there a better way to do it?
0
Can you load all assets inside an Addressable folder? So, I have a folder marked as addressable. This folder has many sub folders, which might have more sub folders, ultimately having some .png images. I would like to load every single Sprite found in my main folder and its children (i.e. recursively). public static AsyncOperationHandle lt IList lt TObject gt gt LoadAssets lt TObject gt (IList lt IResourceLocation gt locations, Action lt TObject gt callback) public static AsyncOperationHandle lt IList lt TObject gt gt LoadAssetsAsync lt TObject gt (object key, Action lt TObject gt callback) public static AsyncOperationHandle lt IList lt TObject gt gt LoadAssetsAsync lt TObject gt (IList lt object gt keys, Action lt TObject gt callback, MergeMode mode) public static AsyncOperationHandle lt IList lt TObject gt gt LoadAssetsAsync lt TObject gt (IList lt IResourceLocation gt locations, Action lt TObject gt callback) The first, third and fourth seem to take a list of keys for individual addressable assets (e.g. the actual Sprites), which is not what I want. I just want to provide the key for the parent folder, and then get all the sprites in it or its sub folders. So, the second function seems a bit promising. I would've expected to use it like this Addressables.LoadAssetsAsync lt List lt Sprite gt gt ("Assets MyMainFolder", myCallback) But it just tells me that the key is invalid. I've made sure that the folder is addressable, it has that key, and the group has been built. So my question is is there a way to load every addressable asset inside an addressable folder? Like how AssetBundles worked. Unity 2019.3.0f3.
0
How to fix infinite jump in Unity 3D? I have the following code public float jumpHeight 3f bool isGrounded void Update() if(Input.GetButtonDown( quot Jump quot )) amp amp isGrounded) velocity.y Mathf.Sprt(jumpHeight 2f gravity
0
Difference between 'max distance' and 'radius' in Physics.SphereCastAll I needed a way to check for all gameobjects within a set sphere of my player object. I found Physics.SphereCastAll which will return a RaycastHit , exactly what I wanted. But, I am having trouble understanding the method signature docs. Basically, it's the two things in the title I am confused on right now From Unity docs radius The radius of the sphere. maxDistance The max length of the sweep. Is 'max length of the sweep' a measurement of time (or degrees?)? I would have thought the length would be the same as the radius (or at least you could calculate it from the radius) but it obviously isn't what I think length means.
0
UnassignedReferenceException The variable player of FollowPlayer has not being assigned My current task is to make the camera follow the moving cube in a stable way where the camera won't get locked in the center of the object so it won't get dizzy once the cube starts to collide or fall down. I have done the parenting right, I have named the cube as the player and then selected it as the Transform reference in the new component that I have created for the camera to follow. But it just says UnassignedReferenceException The variable player of FollowPlayer has not being assigned. and I am unable to get the right results. What should I do ? Here is the C script that I wrote using UnityEngine public class FollowPlayer MonoBehaviour public Transform player public Vector3 offset void Update() transform.position player.position offset My scene setup looks like this So I have un parented the main camera from the player and it works perfectly fine but I still get the error, Have any ideas why?
0
Triangles in the corners of skybox When looking at the corners of skybox this happens http i.imgur.com H8XvS8I.jpg How to get rid of this? 6 skybox textures are 2048x2048px each. Tried changing Near and Far clipping of the main camera inside the character controller but it was ineffective. If I look away from the corners the dark triangles dissapear. Only when I look directly at the corners they appear.
0
How can I handle two collisions in the same frame? My problem is that I have a player with collisions, and enemy can collide with players collision and execute Hurt function in players script. But the problem is enemies can overlap and can hit the player in the literally same frame. So they both execute Hurt function. In my Hurt function I change players collision layer for a 2 seconds, and he is no longer be able to seen by enemies. But it doesnt matter because of the same hit by two or more enemies in the same frame. How can I solve this? I tried bool to check if Hurt function is executed but it doesnt work too... Here is Code on Enemy IEnumerator OnCollisionEnter2D(Collision2D collision) if (collision.gameObject.CompareTag("Player")) buras kediler st ste bindiginde birden fazla kez calisabiliyor charMovementRef.StartCoroutine(charMovementRef.Hurt()) Debug.Log("hasar yedi") Code on Player Hurt should only works one at the same time public IEnumerator Hurt() layer de i tirerek d man collisionlar ndan ka gameObject.layer 9 can azalt health HeartUI() show the new health on UI karakter g r nt s yan p s ns n gameObject.GetComponent lt SpriteRenderer gt ().color new Color(1f, 1f, 1f, 0.5f) player z plat rb2D.velocity new Vector2(rb2D.velocity.x, 0) rb2D.AddForce(new Vector2(0, jumpPower 1.2f)) 2 saniyeli ine colliderlar kapal kals n, sonra eski haline evir yield return new WaitForSeconds(2) gameObject.layer 0 gameObject.GetComponent lt SpriteRenderer gt ().color new Color(1f, 1f, 1f, 1f)
0
Is ArrayLists so slow that it is doomed to kill performance in Unity? I was reading Which Kind Of Array Or Collection Should I Use? The document states to use list for the most performance. "...They are the fastest array in unity. For this reason, built in arrays are the best choice if you need the fastest performance possible from your code (for example, if you're targeting iPhone)...performs significantly faster than ArrayList." I am inclined to use list besides performance issues as well because... If you're using List you won't have to cast objects since it's generic and use a T backing storage (at least .net does this). ArrayList have to cast everything to object and cause boxing with value types. faster for value types as it avoids boxing., strongly typed elements. But it got me to wonder, since everyone seems to favor to make a degrading statement about ArrayLists, is ArrayLists that horrible? If so why does it even exist? Is it more of trace of supposedly deprecated codes?
0
AI using character controller makes unwanted change to it's y position The enemy parent object does not have any colliders except for the character controller. It starts out with y .57 and immediately jumps to y 1.6355 because of my call to CharacterController.Move(.) A code snippet is as follows myTransform.rotation Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(targetPos myTransform.position), rotationSpeed Time.deltaTime) Vector3 forward myTransform.TransformDirection (Vector3.forward) character.Move (forward moveSpeed Time.deltaTime) The above occurs in my update function. I am reluctant to post more code because this is for an assignment. I feel like I've tried everything. Using rigidbodies, I fixed this problem but then the enemies began to overlap when they got close. So I reverted back to character controllers. In either case I have been trying different ways of keeping y constant, freezing it, making the y rotation component zero, you name it. One other thing I'll note is that the enemy moves to this y position regardless of where it is initially placed. My main character also starts a distance in the sky and falls down. It so happens that the y position it ends up is this same one that the enemy teleports to. EDIT Also I am on Unity 5.2 EDIT 2 This is for a script I use to make the AI follow my player. It is similar to many you will find just googling, because I based it off of those. I have even tried other people's scripts and had the same problem. EDIT 3 If I put the enemy lower to the ground (say y .55) he will not pop up like before. However, he doesn't move toward the player anymore.
0
Locomotion system with irregular IK Im having some trouble with locomtions (Unity3D asset) IK feet placement. I wouldn't call it "very bad", but it definitely isn't as smooth as the Locomotion System Examples. The strangest behavior (that is probably linked to the problem) are the rendered foot markers that "guess" where the characters next step will be. In the demo, they are smooth and stable. However, in my project, they keep flickering, as if Locomotion changed its "guess" every frame, and sometimes, the automatic defined step is too close to the previous step, or sometimes, too distant, creating a very irregular pattern. The configuration is (apparently)Identical to the human example in the demo, so I guessing the problem is my model and or animation. Problem is, I can't figure out was it is S Has anyone experienced the same problem? I uploaded a video of the bug to help interpreting the issue (excuse the HORRIBLE quality, I was in a hurry).
0
How to limit and direct player's view in VR? We are making a VR game where the player will look at the world through the eyes of his character who sometimes moves on his own, so the player is only observer. The character will rotate his body on his own and we need to change the orientation of player's camera to look where the character looks. For example, the girl takes his hand and leads her way. It would be very unrealistic if the player's head will be turned 180 from his body and he will walk backwards. It'll allow us to avoid exhausting head rotations. Is it a good idea to guide his view by force by limiting camera euler angles relative to the direction of the body?
0
Exposing type definitions to modders in Unity Note that this question is not about modding assets data and not about security, I plan to rely on community trust. I don't know much about DLL's and I was wondering how I can provide interface and attribute definitions for modders. For Kerbal Space Program modders only have to reference the Assembly CSharp.dll, UnityEngine.dll and UnityEngine.CoreModule.dll files of a games build, to create and compile their own DLLs. Are there certain things I have to do, to mimic this behavior, or does this work out of the box? Are there gotchas to this approach? Will a mods DLL, that was compiled using an older version of Assembly CSharp.dll, break if the Assembly CSharp.dll is updated, even though no types relevant to the mod changed? Will modders be able to use Visual Studios debugging features for their DLLs? Is there a better approach to provide type definitions? My question is related to this question. But I would argue that that question is kind of broad, while mine is about one specific aspect. Might not be needed for the question, but here are the two levels of modding that I would like to support for my game 1. Easier modding I want to compile .cs files of modders that implement special interfaces like IAbility, IItem, etc. I will use Roslyn or cs sript to do so. 2. More advanced modding I also want to load .dll's that modders compiled, allowing them to register their own Types in the games DI Framework, mark methods classes with attributes like CallMethodOnLevelLoad and use Harmony.
0
Do I have to use new keyword for unity single game object? I'm using Unity4. Do I have to use new keyword for single game object? look at the following code. 1. GameObject obj new GameObject() obj Resources.Load("Prefabs Ball", typeof(GameObject)) as GameObject 2. GameObject obj obj Resources.Load("Prefabs Ball", typeof(GameObject)) as GameObject is it the same?
0
Unity Particle System Shuriken Setting particles in code with random row in texture animation? Good day, I'm attempting to randomly generate a space scene (quite large actually) in Unity through C code mainly. So far, I've gotten stunning results up to what image 2 will show you. However, now I'm looking to expand the look with more random particles. So, I've made a texture atlas of 8 in a vertical row, which works on the random setting if you have an emitter and the particle system is called with PS.Play() Assigning different materials would only work on a per particle system basis(which would be new texture PER cloud, so to speak) which is not what I want. So, my question How can I use the Shuriken Particle System's Texture Sheet Animation functionality through code, without having an "active" particle system? More precisely, I wish to use the 'Random Row' feature of it to assign random textures to each particle. Since I can't share my code (due to policies), here is a bit more info on how I do it I create an array with coordinates for each cloud. Assign a particle system to that cloud. Randomly generate all the particles for the cloud with relative offsets. Use PS.setParticles(particlesArray) Using a Texture Atlas consisting of the letters A to H to test, only B showing on all particles. Using a Texture Atlas consisting of the fog particles to test, only 2nd showing on all particles. Thank you DMGregory for the help, I've tested it multiple times and it works perfectly now, I've also went ahead and tweaked a few of my settings just to get a more "clear" space
0
How to flush changes in PlayerSettings inside Editor I have a script which works only in the Editor. The script makes changes inside PlayerSettings. However, the changes made are flushed to the hard drive just after something in Unity is saved for example any scene. We have a script which increments the build version. The described issue sometimes leads to the wrong version committed to Git as the changes a flushed to the disk later. How can I flush the changes of PlayerSettings from the code?
0
How to rotate a rigidbody with a Pid controller I would like someone to describe me how to use a PID controller to rotate a rigidbody with AddTorque to a specific position. (like a spacecraft that rotates the Y axis of rotation towards Camera.forward for example). Can anyone show it to me with a script? Actually I already use this script to rotate with AddTorque but the object almost never stops at the precise point. Vector3 camForward Camera.main.transform.forward Vector3 rbForward rb.transform.forward Vector3 torqueY Vector3.Project(torque, Vector3.up) Vector3 torque Vector3.Cross(camForward, rbForward) rb.AddTorque(torque) rb.AddTorque( rb.angularVelocity)
0
why isn't onTrigger invoking on collision with a trigger or a rigidbody? void onTriggerEnter(Collider other) if (other.gameObject.CompareTag("Pick Up")) other.gameObject.SetActive(false) count count 1 setCountText () This is the methodI want to invoke, on collision of a sphere with another cube. The cube is set as a trigger, and a rigidbody component is attached to both of the objects. Still, on collision, the method is not invoked. Is there anything else that may be done, for this method to execute?
0
AI using character controller makes unwanted change to it's y position The enemy parent object does not have any colliders except for the character controller. It starts out with y .57 and immediately jumps to y 1.6355 because of my call to CharacterController.Move(.) A code snippet is as follows myTransform.rotation Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(targetPos myTransform.position), rotationSpeed Time.deltaTime) Vector3 forward myTransform.TransformDirection (Vector3.forward) character.Move (forward moveSpeed Time.deltaTime) The above occurs in my update function. I am reluctant to post more code because this is for an assignment. I feel like I've tried everything. Using rigidbodies, I fixed this problem but then the enemies began to overlap when they got close. So I reverted back to character controllers. In either case I have been trying different ways of keeping y constant, freezing it, making the y rotation component zero, you name it. One other thing I'll note is that the enemy moves to this y position regardless of where it is initially placed. My main character also starts a distance in the sky and falls down. It so happens that the y position it ends up is this same one that the enemy teleports to. EDIT Also I am on Unity 5.2 EDIT 2 This is for a script I use to make the AI follow my player. It is similar to many you will find just googling, because I based it off of those. I have even tried other people's scripts and had the same problem. EDIT 3 If I put the enemy lower to the ground (say y .55) he will not pop up like before. However, he doesn't move toward the player anymore.
0
What is the best way to create a square grid in Unity? So I need to create a square grid like the one below. And be able to click on a square, the square you chose then is filled with a different color as well as all the squares right and below the square you have chose. My question is what will be the most efficient way to create this grid either in 3D or 2D in Unity.
0
Monster Spawner Reference Issue I have a monster spawner that spawns the quot enemy quot kid which is red, and it has a line in the script where it references the quot player quot gameobject's transform. Before I made the spawner, I had the enemies put by hand and I could reference the player object without issue. Now they're not handplaced, they are spawned from the prefab folder by the spawner. When they spawn the game gives the null reference exception error and stops. I look up to the enemies that are spawned and none of them have the player gameobject referenced. Also when I click on to the enemy prefab to reference the player object, it just doesnt allow me to. How can I resolve this issue?
0
Is Unity NGUI still that usable after Unity has add support for 2D? I am tempted to refactor out the existing component which uses NGUI ("Next Gen UI kit") given that what I needed is only the sprite and texture atlas. Since in the newer versions of Unity those parts are natively supported, is there any reason I should still keep NGUI?
0
Configurable Joint, linear limit range I am working on a physics driven pressable button, but I cannot seem to tackle the minimum and maximum limits. This is the rig I have set up for the button (as it looks when pressed down). 2D view 3D view The idea is that the box collider is a trigger and the button (cylinder, mesh collider) is a rigidbody with configurable joint, locked and limited on a single axis. I am using configurable joint, as that's the only one that supports basic, linear restrictions. I have set up the configurable joint to restrict motion on a single axis, but the joint only allows single dimensional limit, that is applied to both directions. Screen capture of relevant configuration Basically, the opened Linear Limit section is the last property that has been changed for the joint anything else are defaults and irrelevant (at least I haven't found my solution in the properties below, mostly angular stuff). The limit of 0.2 units work, and the button can be pressed it only gets pressed until those 0.2 units and thats the expected behaviour. The unexpected is that sometimes the angle at which I hit the button, adds force to the button outwards from the box, and it moves 0.2 away from it, ending up like this Obviously, the specified limit of 0.2 units constrain the movement in both directions from the anchor, actually resulting in the range of 0.2 to 0.2 (relative to anchor). How, and is it even possible, to restrict the movement only in a single direction relative to anchor?
0
Simulating circular motion with gravitational forces in Unity2D I am currently messing around with a game where you control a black hole and use its gravity to fling planets at targets. I have the gravity calculations working pretty well when the planets start out stationary but I want to take it a step further and have the planets start out in circular orbit around the black hole. Ideally what I want to do is place a planet, provide it with an orbital period, and have it orbit my black hole object in uniform circular motion. To do this I am following these steps Use the objects initial distance from the black hole ( r ) and the given orbital period ( T ) to calculate the standard gravitational parameter of the system ( mu ) via the equation mu frac 4 pi 2r 3 T 2 Find the tangential velocity of the circular motion via the equation v sqrt frac mu r Assign the object an initial velocity with a magnitude of v and a direction perpendicular to the vector between the black hole and the object Every time the Update() function is called, apply a force to the object in the direction of the black hole that represents its gravitational pull F frac mu m r 2 where m is the mass of the object. All of these equations came from the Wikipedia page on circular orbit. When I do all of this I get planets that do orbit the black hole, but their orbits are elliptical and rather unstable while I want them to be perfectly circular. Here is my GravitationalForce script, which I attach to the planet object and provide the black hole object as otherBody. public class GravitationalForce MonoBehaviour public GameObject otherBody public float orbital period 2 float grav param Rigidbody2D rigidbody2d Rigidbody2D rigidbody2d other Start is called before the first frame update void Start() get rigid bodies of this object and the object it is attracted to rigidbody2d GetComponent lt Rigidbody2D gt () rigidbody2d other otherBody.GetComponent lt Rigidbody2D gt () calculate the grav param for this object Vector2 position this rigidbody2d.position Vector2 position other rigidbody2d other.position Vector2 dist vector position this position other float dist dist vector.magnitude grav param (4 Mathf.Pow(Mathf.PI, 2) Mathf.Pow(dist, 3)) (Mathf.Pow(orbital period, 2)) calculate and assign the initial velocity Vector2 dist vector rotated new Vector2( dist vector.y, dist vector.x) dist vector rotated.Normalize() Vector2 velocity vector dist vector rotated (Mathf.Sqrt(grav param dist)) rigidbody2d.velocity velocity vector Update is called once per frame void Update() calculate gravitational force Vector2 position this rigidbody2d.position Vector2 position other rigidbody2d other.position float dist Vector2.Distance(position this, position other) float force magnitude (grav param rigidbody2d.mass) (Mathf.Pow(dist, 2)) float theta Mathf.Atan2(position other.y position this.y, position other.x position this.x) Vector2 force vector new Vector2(force magnitude Mathf.Cos(theta), force magnitude Mathf.Sin(theta)) rigidbody2d.AddForce(force vector) Any ideas on why my orbits are unstable and elliptical instead of stable and circular? My only thought is that circular orbit is a very sensitive state and rounding errors in the physics engine or floating point number weirdness might be causing it to deviate from the circular path. If that is the problem, is there any easy fix to that and if not, what could the problem be? Thanks!
0
Move object to mouse direction without raycast? I have script moving object to mouse postion using raycast. But what I need now is use the mouse movement to move my object. using System.Collections using System.Collections.Generic using UnityEngine public class HoverPanel MonoBehaviour public GameObject ground private Rigidbody rg public float moveForce, speed 2 public Vector3 Mouse pos void Start() rg gameObject.GetComponent lt Rigidbody gt () void Update() rg.AddForce(Input.GetAxis( quot Vertical quot ) moveForce ground.transform.forward) if (Input.GetAxis( quot Mouse X quot ) lt 0) Code for action on mouse moving left print( quot Mouse moved left z quot ) if (Input.GetAxis( quot Mouse X quot ) gt 0) Code for action on mouse moving right print( quot Mouse moved right z quot ) if (Input.GetAxis( quot Mouse Y quot ) lt 0) Code for action on mouse moving left print( quot Mouse moved back x quot ) if (Input.GetAxis( quot Mouse Y quot ) gt 0) Code for action on mouse moving right print( quot Mouse moved forward x quot ) void FixedUpdate() No need to use this RaycastHit hitGround Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out hitGround, 500)) Mouse pos new Vector3(hitGround.point.x, transform.position.y, hitGround.point.z) transform.localPosition Vector3.Lerp(transform.localPosition, Mouse pos, speed Time.deltaTime)
0
How to have an object follow the mouse, even if not clicked in Unity? I have this object. I want to click on it and drag it around. Also if I click anywhere on the screen, I want the object to move but keep the distance. In the script below I made the object follow the mouse, but I can't do the second part. I have a couple rays for debugging. Any ideas? using System.Collections using System.Collections.Generic using UnityEngine public class Player MonoBehaviour Vector3 playerPosition Vector3 mouseF Vector3 mouseN void FixedUpdate() if (Input.GetMouseButton(0)) setMouseF() setMouseN() Debug.DrawRay(mouseN, mouseF mouseN, Color.green) Debug.DrawRay(mouseN, (playerPosition mouseN), Color.red) move the player base on mouse position transform.position mouseF if (Input.GetMouseButtonUp(0)) on mouse release, set the new player position playerPosition mouseF void setMouseF() Vector3 mouseFar new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10f) mouseF Camera.main.ScreenToWorldPoint(mouseFar) void setMouseN() Vector3 mouseNear new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane) mouseN Camera.main.ScreenToWorldPoint(mouseNear)
0
unity destroy enemy when jumping on it I am creating a 2D platformer using Unity3D, I want to have the player destroy enemies when it jumps falls over them (just from the top). But I have been having problems trying to implement this. I stripped everything and used two simple box colliders in order to make it easy. So, when onCollisionEnter2D is called I get the bounds of the objects colliding like this Bounds playerBounds new Bounds(transform.position, collider2D.bounds) Bounds collisionBounds new Bounds(collision.transform.position, collision.collider.bounds) Then I check if the object colliding is below by comparing it's bounds If the player's lowest point is greater than the colliding object's highest, then it is above it bool isAbove playerBounds.min.y gt collisionBounds.max.y Then I check if the object is actually an enemy, and if so, I destroy it if(isAbove) if(collision.gameObject.tag "Enemy") collsion.gameObject.getComponent lt EnemyController gt ().die() Now the thing is this never happens, isAbove is never true, so I tried checking the heights of each object so I use Debug.Log("player " playerBounds.min.y " enemy " collisionBounds.max.y) It says the player bottom most is below the enemy top most. Since I use this same method to detect if the player is grounded in order to enable jumping I noticed it works beautifully with other things like platforms but not with enemies. Also y used Debug.break to stop the game and noticed that when colliding with platforms the player's collider was always above the platform's, but when it collided with enemies they overlap so the player's bottom most part is below the enemy's top most part. I read somewhere that this is due to the minPenetrationPenalty property, I didn't like the results of messing with it so I just left it the same (If I lower it doesn't even work with platforms, and I increase it they don't even touch and the collision is detected). I tried to compensate for this penetration when checking the bounds so I said bool isAbove playerBounds.min.y gt collisionBounds.max.y 0.01 It sometimes fails and sometimes not depending on the angle and other stuff, I still don't get it because if this was the problem It shouldn't work with the platforms either but it does, it only fails with enemy. I even tried to check for the overlap and said float overlap playerBounds.min.y collisionBounds.max.y bool isAbove overlap gt 0.01 this still works beautifully with platforms only reporting positive values (which means they are not overlapping), but with enemies it actually reports negative values (which confirms the previous they do overlap), even more strange it actually reports overlaps greater than what should be allowed, the usually report a 0.09 which means a 0.09 overlap which is greater than the 0.01 that the physics engine is supposed to allow. If I apply this code in OnCollisionStay2D instead it works, I guess by this time the overlap is fixed, but this looks unnatural and I still don't understand why this works perfectly with platforms (they never even overlap!) and not my enemies.
0
Problem with shooting So what I am trying to achieve is have the player shoot toward the mouse positiion and I have that working but I want the player to have to charge their shot. So if the player just presses the button it only goes a certain distance but if the player holds the button down for a bit it goes farther. I tried to make a video that kinda explains what I am going for. This is the code that controls the shooting public class BowController MonoBehaviour public GameObject arrow public Transform shootLoc public float force public Camera cam public float chargeMin public float chargeAmount public float chargeMax public bool charging void Start () void Update () Ray cameraRay cam.ScreenPointToRay(Input.mousePosition) RaycastHit hit Vector3 pointToLook if (Physics.Raycast(cameraRay, out hit, 50)) pointToLook hit.point Debug.DrawLine(cameraRay.origin, pointToLook, Color.blue) else pointToLook cameraRay.origin (cameraRay.direction 50) transform.LookAt(pointToLook) if(Input.GetMouseButtonDown(0)) charging true if (charging) Charging() if (Input.GetMouseButtonUp(0)) GameObject tempArrow tempArrow Instantiate(arrow, shootLoc.position, shootLoc.rotation) as GameObject tempArrow.transform.LookAt(pointToLook) Rigidbody tempBody tempBody tempArrow.GetComponent lt Rigidbody gt () tempBody.AddForce(transform.forward force, ForceMode.Impulse) force 100 charging false void Charging() force Time.deltaTime chargeAmount if (force gt 500) force 500 And this is the code that is on the arrow public Rigidbody rBody public float speed void Awake () flying true void Update () if (flying) rBody.velocity rBody.velocity.normalized speed transform.LookAt(transform.position GetComponent lt Rigidbody gt ().velocity) transform.Rotate(0, 180, 0) void FixedUpdate() if (flying) transform.rotation Quaternion.LookRotation(rBody.velocity) void OnCollisionEnter(Collision collision) flying false I am still pretty new to coding so any help is appreciated. Thank you all very much in advance for the help!
0
Need help with using Player Prefs to save number of coins collected I'm using unity 3D to make a game where the character collides with coins in order to collect them. When playing the game, the player should start out with zero coins and each time he collides with a coin, the amount should increase by one. On a main menu scene, the total number of coins (that have been collected across multiple games) should be displayed. The total number of coins is being displayed on the main menu but once in the gameplay scene, the total number of coins is being displayed there too (where it's supposed to start at 0 and then increase by 1 each time a coin is collected). Here is the script I use for when the player collides with a coin using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class CoinScript MonoBehaviour void OnTriggerEnter(Collider target) CoinScoreManager.coinAmount 1 Destroy(gameObject) Here is the script I use to manage the UI and coin number in the game play scene using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class CoinScoreManager MonoBehaviour public static int coinAmount public Text coinText void Start() coinAmount PlayerPrefs.GetInt( quot CoinAmount quot ) void Update() coinText.text coinAmount.ToString() PlayerPrefs.SetInt( quot CoinAmount quot , coinAmount) Here is the script I use to manage the UI and total coin number in the scene with the main menu using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class MainMenuController MonoBehaviour int coinAmount public Text coinAmountText void Start() coinAmount PlayerPrefs.GetInt( quot CoinAmount quot ) void Update() coinAmountText.text coinAmount.ToString() I think the problem is in the second script shown above. In the Start function I'm calling the coinAmount which is the same variable used to show the total coin number. I think that's the problem but I'm not really sure how to fix the problem as I'm still kinda of new to Unity and programming. Please let me know if there's anything else you need to know about the game in order to figure out how to fix this. Thanks for your help!
0
Detect when item has been dragged dropped onto an inventory slot In my inventory system I want to be able to drag and drop items into inventory slots. I managed to make it work, but only in a weird way When the player starts dragging, it picks up the item and it follows the mouse's position. When they release the button outside the inventory, the item's position is restored to the slot from which it was picked up. I use GameObject mouseReleasedObject eventData.pointerCurrentRaycast.gameObject to detect whether the drag was released over an inventory slot. The problem is that when the player drops it on a possible inventory slot, the same quot restore to previous slot quot behaviour happens. That's because the mouse is top of the dragged item and the slot as well but the item is rendered above everything else. How can I make the dragging ignore the item itself, and detect the slot underneath? Start dragging public void OnBeginDrag(PointerEventData eventData) GameObject draggedObject eventData.rawPointerPress if(draggedObject.GetComponent lt RectTransform gt () is null) return if(draggedObject.tag quot InventoryItem quot ) Debug.Log( quot InventoryItem drag has started! quot ) dragStartSlot draggedObject.transform.parent.gameObject draggedItem draggedObject draggedItem.transform.SetParent(canvas.transform) draggedItem.transform.SetAsLastSibling() End dragging public void OnEndDrag(PointerEventData eventData) GameObject mouseReleasedObject eventData.pointerCurrentRaycast.gameObject if(draggedItem is null) return Debug.Log( quot Released at quot mouseReleasedObject.gameObject.name) if(mouseReleasedObject.transform.tag quot InventorySlot quot ) if(mouseReleasedObject.transform.childCount lt 1) the inventory slot is empty, we place here the item! draggedItem.transform.SetParent(mouseReleasedObject.transform) draggedItem.GetComponent lt RectTransform gt ().localPosition Vector3.zero else the inventory slot is taken, we swap the items! else the item is not released on a proper slot, we restore it's position! draggedItem.transform.SetParent(dragStartSlot.transform) draggedItem.GetComponent lt RectTransform gt ().localPosition Vector3.zero
0
Unity how to implement a sound detection ? I want to trigger an event if an enemy (or player) can hear a sound generated from other enemy player. How to implement a sound detection system ? Thanks
0
Unity tilemap collider not colliding with rigidbody In the wireframe you can see the tilemap collider for this hill. The red circle falls right through however. The circle has a 2D rigidbody attached. Everything is on the Default sorting layer and on layer order 0.
0
Unity and Chartboost loading problems I implemented chartboost in my ios game and locally it wors great. I can receive ads. Now my game is online but in the google analytics I get only error messages from the game, meaning the chartboost ads fail to load. Here https www.dropbox.com s cft98lk27mt7p3s cb.jpg?dl 0 The iage show google analytics registering only failed loads and there is no single successfull ad load? What could be the problem here?
0
Why the Vector3.Dot value is 12 when running the game? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using UnityEngine.Events using System public class InteractableItem MonoBehaviour public string currentMode private Transform player private InteractableMode currentInteractableMode private string currentDesription private float originDistance private void Awake() player GameObject.Find( quot Player quot ).transform originDistance transform.GetComponent lt InteractableItem gt ().distance public enum InteractableMode Description, Action, ActionWithoutThrow public enum ViewMode FrontView, AllView public ViewMode viewMode ViewMode.AllView public InteractableMode interactableMode InteractableMode.Description public float distance TextArea(1, 10) public string description quot quot public bool IsAnyAction() return interactableMode InteractableMode.ActionWithoutThrow interactableMode InteractableMode.Action public bool IsActionWithoutThrow() return interactableMode InteractableMode.ActionWithoutThrow private void Start() currentMode GetComponent lt InteractableItem gt ().interactableMode.ToString() currentInteractableMode GetComponent lt InteractableItem gt ().interactableMode currentDesription GetComponent lt InteractableItem gt ().description private void Update() var heading transform.position player.transform.position var dot Vector3.Dot(heading, transform.forward) if(viewMode ViewMode.FrontView amp amp dot lt 1) transform.GetComponent lt InteractableItem gt ().distance 0 if (viewMode ViewMode.FrontView amp amp dot gt 1) transform.GetComponent lt InteractableItem gt ().distance originDistance The script is attached to some objects and one of them the ViewMode is set to FrontView and then when running the game first time the dot value is 12 and then it's getting inside and going the line if(viewMode ViewMode.FrontView amp amp dot lt 1) transform.GetComponent lt InteractableItem gt ().distance 0 but it should not set the distance to 0. only if I'm getting close enough to the item then it should see the item from the front and then only if I'm moving the player behind the item the dot should be minus and set the distance to 0 but for some reason the dot is minus 12 when running the game so it's setting the distance to 0 right away.
0
Tilting a game object left right forward back with gyroscope, regardless of player's heading I'm working on a mobile game in Unity and using the gyroscope to rotate an object along the x and y axes. float x Input.gyro.attitude.x float y Input.gyro.attitude.y This code give me the rotation I want when pointed in a certain direction along the z axis. I want the rotation to not depend on the z axis. I want the rotation to act the same no matter what direction I'm pointed in the real world. Here is a 12 second clip of what I get using a mobile gyroscope when pointed at 1 or North on the z axis I want the rotation to be the same no matter what direction I am pointed on the z axis with the gyroscope. Is there some way to rotate the whole coordinate system?
0
Triggering animation in character OnTriggerEnter? I've been stuck on this for hours. I have a character whose animations are based in mecanim to transition based on the bool variable ShivaEnter. One invisible cube is set to change the bool value from false to true and vice versa OnTriggerEnter. The code is as follows using UnityEngine using System.Collections public class PontyAnimations MonoBehaviour SerializeField private Animator animator private GameObject ponty private GameObject ponty void Awake () animator GetComponent lt Animator gt () void OnTriggerEnter (Collider other) if (other.gameObject.tag "Player") animator.SetBool ("ShivaEnter", true) void OnTriggerExit (Collider other) if (other.gameObject.tag "Player") animator.SetBool ("ShivaEnter", false)
0
Build displays black screen with static Something really odd happens when I'm trying to load a scene. It is supposed to look like this (it also has to show the next scene after loading) What is going on?
0
Instantiate prefab button inside of panel I have a Canvas GameObject with a panel inside of it and a button prefab of the default button. When I drag the button from my resources folder onto the Canvas in the hierarchy, it places itself where I expect it to, into the panel. However when I instantiate it like below GameObject button Instantiate(Resources.Load("UI Dialogue Button"), new Vector3(0, 0, 0), Quaternion.identity, MyCanvas.transform) as GameObject it gets placed into the center of the screen because of the second parameter. However, I can't set it as a child of the parent because that doesn't happen until the last parameter. It also doesn't feel right to figure out the exact Vector3 to plug in so that it looks like its on top of the panel. Is there a way to instantiate the button onto the panel in code as it works when dragging it from the resources folder onto the Canvas in the hierarchy?
0
Unity C Array Scripting! I was just trying and make a simple 2D game. I have a simple circle sprite (red, green and blue). These circles fly upwards with my scripting as shown below public class Direction MonoBehaviour public GameObject ballons public float increase public float timeInterval public float timeForGetGo public float increaseInterval public float startTime public float timeForNextSpawn public Transform instantiatePos void Start () StartCoroutine (direction ()) void Update () increase increaseInterval direction () Instantiater () IEnumerator direction () while (true) foreach (GameObject gameObjects in ballons) gameObjects.transform.position new Vector3 (gameObjects.transform.position.x, gameObjects.transform.position.y increase, 0f) yield return new WaitForSeconds (timeInterval) So, instead of making them fly with one script by one script, which I normally do, I tried to make array of these gameObjects and make them go upwards. It worked great! But, I have a problem. I want these upward going circle to instantiate but when I instantiate them, they won't go upwards as they aren't in the list of arrays I put earlier as in public GameObject ballons in first line in that script. So, as in conclusion, my problem is the instantiated objects won't have same property coz the script is attached to another gameobject and not in the original gamobject itself. Any ideas?
0
Make a game object move inside circle and bounce from walls without gravity I have a circle with a RigidBody2D and CircleCollider2D components on it. I'm trying to make it move constantly inside a bigger circle without gravity involved, make it bounce off the circle walls like it has constant velocity but without any delays, same speed all the time. Here is an example of the same behaviour but inside a rectangle I would like to do the same but inside a circle and detect the collision with the circle walls Thanks in advance )
0
Black screen after running emulation mode in the Unity Editor for hololens I am having issues with black screen when running the emulation mode or simulator for Microsoft hololens. In the preview the camera shows what the user should see. I see no obvious reason to behave like this and no error warning is given. I am using code snippets from the Origami tutorial,except I chose to use RayCastNonAlloc. Movement.cs public class Movement MonoBehaviour public GameObject person public float seconds private Vector3 point new Vector3(0,0,0) private RaycastHit rayHit new RaycastHit 5 void OnSelect() person.transform.position Vector3.Lerp(person.transform.position, point, seconds Time.deltaTime) Update is called once per frame void Update() if (Physics.RaycastNonAlloc(Camera.main.transform.position, Camera.main.transform.forward, rayHit, Mathf.Infinity, 0) gt 0) foreach (RaycastHit hit in rayHit) point.x Mathf.Clamp(hit.point.x, 290f, 6970f) point.y Mathf.Clamp(hit.point.y, 40f, 1860f) point.z Mathf.Clamp(hit.point.z, 1700f, 140f) Scene.cs using UnityEngine using UnityEngine.XR.WSA.Input public class Scene MonoBehaviour public GameObject cursor public GameObject Focused get private set public Scene Instance get private set private GestureRecognizer recognizer private MeshRenderer Renderer private readonly RaycastHit rayHit new RaycastHit 5 void Awake() Instance this recognizer new GestureRecognizer() recognizer.Tapped (args) gt if (Focused ! null) Focused.SendMessageUpwards("OnSelect", SendMessageOptions.DontRequireReceiver) recognizer.StartCapturingGestures() Renderer cursor.GetComponent lt MeshRenderer gt () void Update() GameObject oldFocused Focused if (Physics.RaycastNonAlloc(Camera.main.transform.position,Camera.main.transform.forward,rayHit,Mathf.Infinity, 0) gt 0) Renderer.enabled true foreach ( RaycastHit hit in rayHit) cursor.transform.position hit.point cursor.transform.rotation Quaternion.FromToRotation(Vector3.up, hit.normal) Focused hit.collider.gameObject else Focused null Renderer.enabled false if (Focused ! oldFocused) recognizer.CancelGestures() recognizer.StartCapturingGestures()
0
Import blender camera with key frames to unity? I am wondering if I can take a camera tracked camera from blender and import it into unity. Is there any way to do this? Please let me know! Thanks in advance.
0
Why Unity Navmesh codes should be executed first? I'm trying to calculate path using NavMesh.CalculatePath and use rigidbody alongside with it, how ever if character does not stick to navmesh baked area the calculatePath codes will not work. I also found that if my path finding codes does not run first the path finding will not work either. for example void Update path finding in this script will work PathFinding() GetDistance() void Update path finding in this script will NOT work GetDistance() PathFinding() any help regarding to solving the problem or understanding how Unity navmesh system works will appreciated.
0
Comparing analog stick movements to predefined flick shapes I want to create a control scheme similar to the EA Skate games, where flicking the right analog stick in various ways makes the character do various tricks I record the user input over a set amount of time or until the user moves the analog stick back to its resting position. The recording is a List of Vector2 Coordinates. Depending on how fast the user flicks the analogue stick, I sometimes get a shorter (15) or longer (45) list of points. Now I want to compare these lists of points to predefined shapes like the ones in the screenshot, to match which action the player intended to take. My idea was to use some metric to compare the similarity of the recording to lists of arrays, however, I don't which metric I might use. I found the Hausdorff Metric and it seems applicable, but I don't know how to implement it. It might also be an overkill for the problem, so I wanted to ask, how other people would solve the problem.
0
How to manage collision of two player ? I'm developing a multi player car game. Suppose that car A hit car B both A and B have Rigidbody and collision functions attached. Because car A hit car B i want to take actions only to car A (add or remove point) but not to B. So i need to identify that car A is 'hit' (with guilty ) car B that has no 'guilty'. Can you suggest me how to do ?
0
Black stripes at the junctions of road segments I made a simple runner where the road is dynamically generated, and the sphere together with the camera moves with the help of Rigidbody velocity, but the problem is that black bars appear at the joints between segments, and if you add an AddForce sphere, then the sphere at the joints jumps which should not be. How to solve this problem I checked the positions of the segments, they fully correspond to the desired ones, that is, there are no gaps between them, I use the standard shader Segments 10.4 units in size. Imported from Blender, but if you take the standard cube model then the same thing (black bars), so that s not the point. Positions between these segments The segment before (on which the sphere in the screenshot) and the next segment Road Material Settings
0
How to get good movement synchronization in a networked game (action shooter) I've spent the last two days trying to get good movement interpolation with Photon in Unity but I can't get anything that I'm happy with. I've tried several methods but none satisfied me. My understanding is that I better use some kind of interpolation (as opposed to extrapolation dead reckoning) because in my game the players can change direction fast. I've tried lerping between the current position and the last received authorized position, I've tried lerping between the old and the new authorized position, but nothing gives me the right amount of responsiveness smoothness. What can I do? Sample code public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) if (stream.IsWriting) do we have authority over this object? stream.SendNext(transform.position) stream.SendNext(transform.rotation) else newNetworkTime Time.time oldPosition transform.position oldNetworkPosition networkPosition networkPosition (Vector3)stream.ReceiveNext() networkRotation (Quaternion)stream.ReceiveNext() void RemoteMovement() float t 1.0f ((newNetworkTime interpolationPeriod Time.time) interpolationPeriod) transform.position Vector3.Lerp(oldPosition, networkPosition, t) transform.rotation Quaternion.Lerp(transform.rotation, networkRotation, Time.deltaTime movementSpeed)
0
How to make a 'Picture book Cutscene' in Unity 2D with simple 2D images? I'm trying to implement a simple cutscene system in my Unity game, preferably one that allows cutscenes to play at the start and end of each of the levels. What I was imagining was pretty similar to A Hat in Time's 'storybooks' from it's time rifts, but full screen and advanced with a single key. The images are simple and comic like, and I was wondering how to implement such a feature since it feels like it's a bit different to Unity's pre existing Timeline system, as there isn't many moving parts. How do I go about approaching this problem? At least, I don't know how to get the project to a state where a person can press a key to turn to the next page (whether or not there's a visual transition to the next is optional) and once it's done, to start the actual level scene. Do I still use the Timeline for this? I know I could potentially use an empty game management prefab in order to set up when to play the cutscenes, however.
0
How to manage "jump" in my 2d platform game? I'm developing a simple 2d platform game with Unity 2d. I have a problem managining my "Jump" action for the player. I would like the player to Jump only when he has his feet on a "surface" terrain, platform, crate etc. I'm considering using colliders when my player collides with a surface, set my bool canJump true. When he jumps, I set canJump false (he is midair). My terrain has a Rigidbody2d is Kinematic and a Box Collider 2d. My Player has a Rigidbody2d is Dynamic and a Capsule Collider 2d (or a Polygon Collider.. ) The events OnCollisionEnter2d() and OnTriggerEnter2d() are never raised when Player collides with terrain. Does anyone know what's wrong? Thanks EDIT Now i'm using this to check if "something" is under my feet RaycastHit2D hit Physics2D.Raycast(rb.transform.position, Vector2.up, 0.1f) if (hit) canJump true It doesn't works! hit is always true! I'm getting mad!
0
Unity Passing an array in a shader I want to pass my array (which is inside my c code) to my shader. Shader "custom shader4" Properties myArray("Array", Float 256 ) SubShader Pass CGPROGRAM public float myArray 256 code... this is obviously not working. Is anyone here who knows how to solve this? (also in c ) myMaterial.MyArray anotherArray It has to be something like this right? Or do I need a workaround?
0
Rigged through Blender (Rigify) and Errors in Unity I am working on a Unity scene and as the 3D model is missing the bones, I ended up going to Blender for the rigging. For that, I followed the procedure that Unity suggests by using the add on Rigify. I was also following this tutorial, which was really helpful. After exporting from Blender (in .fbx) and importing it on Unity, I went through the configurations (as vcard suggested here) In the "Rig" section, I pressed the button "Configure" (to configure the Avatar Definitions) and came across an error "Character is not in T pose". I solved this one quite fast by accessing the menu "Pose" (in the Inspector) and then "Enforce T Pose". After that, back in the scene, I came across the following error on the Inspector Invalid Avatar Rig Configuration Missing or invalid transform Required human bone 'Head' not found. I went straight to the configurations and decided to add the specific bones to the Head that appeared on the inspector (in the Avatar Definitions configurator). With that, I came found out that the problem is really the organization where there were placed by Rigify. Any guidance is appreciated.
0
What is the bare minimum I need to set up the Android SDK for Unity development? I want to import my Unity project to Android, and I need to download the Android SDK, but I do not want to download any unnecessary components. Do I need to download all platforms, or just the latest one? I am worried about the size of Android 7.1.1 (API Level 25) the SDK Manager reports this as the latest version, but I am not sure. I only want to import my project for Android smartphones, with no plan of publishing it. I do not want to build to Android TV or Android Wear, for example. Do I need to download all of the contents under the specific platform? I ask because there are Android TV and Android Wear system images, and the files can get quite large.
0
How can I change the highlighted color of a Unity button when it's clicked? I was playing around with buttons in Unity, and I wanted to see if I could change a button's highlighted color every time I clicked on it. I added a script in the same GameObject as a button component, and I had a changeColor function attached to the component's OnClick(). The function was in a ButtonScript class written like this public class ButtonScript MonoBehaviour public Button button public void changeColor() Debug.Log ("Changing highlighed color") int r Random.Range (0, 255) int g Random.Range (0, 255) int b Random.Range (0, 255) Color currentColor button.colors.highlightedColor currentColor.r r currentColor.g g currentColor.b b I couldn't do button.colors.highlightedColor new Color(r,g,b) because I got a "Consider storing the value in a temporary variable" error. When I tried a test play and clicked the button multiple times, the highlighted color didn't change. How can I make a function that changes a button's highlighted color when it's clicked, if it's possible?
0
How to make a collider the follows all the animations of a prefab? I have attached a capsule collider with my player(prefab) and made a script so that when Space key is down it does the jump animation in Unity. But because of the collider not jumping with the player, the player gets stopped by obstacles though he visually passed it. How can I make a collider that moves with my animations attached to a prefab?
0
Load large quantities of data in Unity3D I'm building an Android app using Unity3D where users can visualize data immersively. The data is immutable and stored using a MySQL database hosted on cPanel. When the user clicks a button in the environment, it starts the creation of a chart. First, contacts a .php file present in the server responsible to query the database, fetching the data and make it available to the Unity controller which then adds the points to the chart. This works fine for small quantities of data. To increase performance, thought of exporting from MySQL as CSV and transform to one JSON, instead of querying a database or try to make MySQL transform to JSON, but I'm afraid this won't be enough. Could also extract as CSV and use a 3rd party for reading it. How would you load the data in such case to have the best performance?
0
NavmeshAgent not to turn back Imagine the blue part of this picture is streets and navmesh. the red object is a car with navmeshAgent. the green circles are the colliders set as triggered and they are the destination of the car. when the game starts the car will choose one of them and go to that , after reach that it will choose another one randomly so it means the car will go through all of this forever. now the problem is sometimes when car reach's one them and choose another since it will choose the closer path to next destination sometimes it will have to turn back which its not realistic and doesn't make sense. as you can see in this example when reach that point since the middle one is closer from where the car is triggered it will turn back and the red arrow is wrong path , instead it should go through the green arrow and that's the correct path. how can i do something to not to turn back instead find another way?
0
Need help with my on collision restart program I tried using the program using UnityEngine private void OnTriggerEnter(Collider other) if (other.tag "setting object tag") Application.LoadLevel(Application.loadedLevel) But the OnTriggerEnter command came up with an error saying "a namespace cannot directly contain members such as fields or methods". And the Application.LoadLevel(Application.loadedLevel) program had an error saying "application.loadedLevel is obsolete, use sceneManager to determine what scenes have been loaded".
0
Circle Collider 2d is slipping off box colider2d when it shouldnt I have a crude rectangle sprite with a box colider 2d, and a circle sprite with rigidbody 2d and circle collider 2d, as seen in the image below. When I click on the red rectangle, it moves up fairly quickly a little more than the diameter of the circle. If this occurs from the position show, or with the circle any further right than it currently is, the circle appears to fall down onto the yellow box almost instantly, hugging the side of the red rectangle. If I let the circle go a little more onto the red rectangle then it is pushed up correctly. Why is the circle falling off the red rectangle from this position, and how can I prevent it from acting like this?
0
Switching between meshes vs Loading only specific mesh I am currently developing an online multiplayer game on Unity. In the game, the character of each player will be assigned its mesh after the game receives parameters (their meshes' names) for each character from the server. Assigning each character's mesh can happen after the main scene is loaded. I am wondering whether I should make each character's object the same by having every mesh possible loaded into it and only activate the corresponding mesh for that player. I should create a class that holds every mesh possible (like, mesh manager) and tell each character to use its mesh from that class. I should delay the characters' meshes loading to wait for the parameter from the server first. Then, load the mesh after the scene has been loaded. I am not sure if specific assets can be loaded outside of its scene in Unity. If anyone has any different solutions, feel free to suggest. Thanks in advance.
0
Enemy shake vibrate when following character I am using the arongranberg A path finding project to create way points for one enemy to follow the player. However, the enemy vibrates back and forward by about 0.1 0.2 unit distance when moving. I have done a lot of research regarding this problem in the past few days but to no avail I could not find a solution that solves it. This is link to a gif to show what I mean. I have tried, changing Application.targetFrameRate 30 changing fixed update to update and vice versa using rigidbody2d and turn interpolate on plus using velocity to move turning iskinematic on and off using translate to move. none of the above solution works. Below is the script I have for my enemy. Any advice would be appreciated. using UnityEngine using System.Collections Note this line, if it is left out, the script won't know that the class 'Path' exists and it will throw compiler errors This line should always be present at the top of scripts which use pathfinding using Pathfinding public class AstarAI MonoBehaviour The point to move to public Transform target private Seeker seeker The calculated path public Path path The AI's speed per second public float speed 200 The max distance from the AI to a waypoint for it to continue to the next waypoint public float nextWaypointDistance 0.02f The waypoint we are currently moving towards private int currentWaypoint 0 Rigidbody2D rb public void Start () rb this.GetComponent lt Rigidbody2D gt () seeker GetComponent lt Seeker gt () Start a new path to the targetPosition, return the result to the OnPathComplete function seeker.StartPath( transform.position, target.position, OnPathComplete ) public void GoToNewTarget(Transform newTarget) path null currentWaypoint 0 nextWaypointDistance 0.02f target newTarget seeker GetComponent lt Seeker gt () seeker.StartPath( transform.position, target.position, OnPathComplete ) public void OnPathComplete ( Path p ) Debug.Log( "Yay, we got a path back. Did it have an error? " p.error ) if (!p.error) path p Reset the waypoint counter currentWaypoint 0 public void Update () if (path null) We have no path to move after yet return if (currentWaypoint gt path.vectorPath.Count) Debug.Log( "End Of Path Reached" ) return this.GetComponent lt Rigidbody2D gt ().MovePosition (path.vectorPath currentWaypoint ) Debug.Log (path.vectorPath currentWaypoint ) Direction to the next waypoint Vector3 dir ( path.vectorPath currentWaypoint transform.position ).normalized GetComponent lt Rigidbody2D gt ().velocity new Vector2 (dir.x 3, dir.y 3) Vector3.MoveTowards(transform.position, path.vectorPath currentWaypoint , 2 Time.fixedDeltaTime) dir speed Time.deltaTime rb.velocity dir this.gameObject.transform.Translate( dir ) Check if we are close enough to the next waypoint If we are, proceed to follow the next waypoint if (Vector3.Distance (transform.position, path.vectorPath currentWaypoint ) lt nextWaypointDistance) currentWaypoint return
0
Health zone heals player but I have a problem Hello I am creating a special health zone that gives the player health and my current scripts health is going up super fast and I want it to go up by 2 hp per second. How would I do this? Here is the health zone script. public PlayerHealth playerHealth public float healthGain 2f void OnTriggerStay2D(Collider2D other) if (playerHealth.currentHealth lt playerHealth.maxHealth) playerHealth.currentHealth (int)healthGain playerHealth.healthBar.SetHealth(playerHealth.currentHealth) if (playerHealth.currentHealth gt playerHealth.maxHealth) playerHealth.currentHealth playerHealth.maxHealth playerHealth.healthBar.SetHealth(playerHealth.currentHealth)
0
Unity3d High level literature Is there any high level literature for mid professional programmers for Unity? There are a lot of tutorials for beginners, but I can't find anything about main API, pipeline or engine architecture. Recommend, please!
0
How to Detect Mesh Segmentation? I have a mesh like this (it's all a single mesh) How I can figure out that the one floating piece is completely disconnected from the rest of the mesh?
0
Is there a way to reference Unity UI object inside native code? Let's say we have a scene in Unity with canvas and InputField on it. Is there a way i can reference my InputField inside native plugin? Maybe i can pass it from Unity?
0
Detecting internet Connection on Unity connection to serve ads How can you detect someone's Internet connection in Unity? I see a lot of forums where people make a request to any site (mostly google.com) to check it, but it does not seem to be an elegant solution. With 3G 4G connections to serve Unity ads or admob interstitial, it takes a lot of time and crashes the game. Regards!
0
Rotating A 2D Cannon Based On Mouse Position I'm creating a game like bubble shooter, I have a cannon which is in the image bellow I want to rotate the cannon based on mouse position. So far I tried various solutions I found over the web but non of them are working, I know that I only need to rotate the cannon on the Z axis because this is a 2D game, so I don't touch X and Y axis. Does anybody know how can I rotate the cannon based on mouse position? Or at least provide me a sample script on where to start. Thank You.
0
what is use of ScriptableSingleton in Unity? in unity 2020.x Unity just has introduced scriptable Singleton. a class that derives from Generic Class Called ScriptableSingleton its like singleton but you only can have single instance of it and seems to be good for ScriptableObjects that need to be Forced to be Single. but there are some differences. they can be project Specific or Shared. they can get any format and unlike usual scriptableObjects they have no visualization in the inspector. the question is how should i use them and they are appropriate for which approaches? this is the link to the reference https docs.unity3d.com 2020.1 Documentation ScriptReference ScriptableSingleton 1.html
0
EnemyAI rotating on Y axis in opposite direction After a battle flag has gone off and the player has entered an enemy's battle zone I want to keep track of the player when it moves and make sure the enemy's Z axis is always pointing towards the player. Upon the player entering the battle zone, the enemy automatically marks the player as its target However there is a chance that the Z axis may not be pointing towards the enemy's target when the battle is first initiated. I decided to shoot a ray cast from the Z axis of the enemy when the battle flag goes off and rotate the enemy until the ray and the player intersect thus telling me that enemy's Z Axis is lined up correctly. the enemy always has a reference to its current target. My idea was that as once the enemy spots its target initially, it can save the position of the most recent spotting and then take the delta of the CurrentTargetPosition.x and the LastSpottingPosition.x If the delta is positive rotate right and if the delta is negative rotate left. THE ISSUE my math or logic must be flawed somewhere because although it works sometimes, other times the enemy will randomly rotate itself in the opposite direction and the ray cast will essentially take the long route to hit the player instead of the shortest route as intended. Also the Local Origin of the enemy and the player are at different height respectively but I dont think that should matter in my case Code Below. create ray from enemy position orgin and point it on the Z Axis Ray ray new Ray(CurrentEnemyTransform.position, CurrentEnemyTransform.forward) RaycastHit hit if (Physics.Raycast(ray, out hit, 50f)) Debug.DrawLine(ray.origin, hit.point) ray hits current enemy target if (hit.transform CurrentTargetTransform) check if enemy has seen its target before while in this battle or is it the first time if (enemy.hasTargetLastPosition) replace old last seen position with most recent spotting enemy.ReplaceTargetLastPosition(hit.transform.position) or add the first spotting of target while in this battle else enemy.AddTargetLastPosition(hit.transform.position) ray is not intersectiing with the enemy's current target so rotate to look for it if (hit.transform ! CurrentTargetTransform) check if enemy has seen its target once before in battle if (enemy.hasTargetLastPosition) since last spotting has my target moved more to the left or right? if (enemy.targetLastPosition.value.x gt CurrentTargetTransform.position.x) rotate right CurrentEnemyTransform.Rotate( Vector3.up, 5f, Space.Self) rotate left else CurrentEnemyTransform.Rotate(Vector3.up, 5f, Space.Self) never seen target yet during this battle so default rotation to right till you found it else CurrentEnemyTransform.Rotate( Vector3.up, 5f, Space.Self)
0
Best way make static GameObject clickable 2D I've built a turn based battle combat game (like pokemon) but i'm stuck between a rock and a hard place. Asfar as i understod UI elements should be inside Canvas, while Players, Enemies, Items and etc... Should not be inside a canvas. Correct me if i'm wrong. I've tried different ways how to handle this situation. Such as make Enemy as a button, but seems not to fire. Since i think it has to be inside a canvas. Also make enemy which have animations as button, may not be a good idea? Update event, to check if the mouse is down and mouse position is converted with screentoworldpoint and see if the positions matches with the enemy position. Update event, to check if the mouse is down and rayCast see if we colide with something. But i dont feel like this is neccesary since the enemy does not move. So the position is always the same. Also if it's possible to take into consideration that every enemy is different size. But this is a minor detail, i would like firstly tackle the best way handle onClick event without the extra overhead. I would appericate any feedback on my dilemma.
0
How to add prefabs to the terrain and still retain scripts, colliders, etc.? I have been working on an old DOS styled game, and I began work on the trees for my terrain. Here is a group of them They, right now, are simply objects in the scene. This works, but is very cumbersome when mass placing them. I want to have them part of the terrain. I tried simply adding them as a detail mesh, but they didn't retain scripts nor colliders. Is there a way to accomplish this?
0
How do I find the name of the current audio clip being played? I have a title scene and a credits scene that use the same music. When I start my game the title scene music plays, and I have my game set up so the audio manager is not destroyed on load. When I enter my credits scene I do not instruct any new music to play, but each time I reload my title scene the title music restarts because a script in the scene tells it do so. How can I get the name of the current audio track so that I will only play audio if it differs from what's currently being played? This is my "LevelMaster" script which is responsible for handling the audio in each scene. public class LevelMaster MonoBehaviour private AudioManager AudioManager SerializeField private string trackName private void Start() AudioManager GameObject.Find("AudioManager").GetComponent lt AudioManager gt () AudioManager.Play(trackName) public void PlaySound(string soundName) AudioManager.Play(soundName) public void StopSound(string soundName) AudioManager.Stop(soundName)
0
Record video and sound from device camera and show it as a texture I need to record and show video from a real camera device in iOS Unity and show that video as a texture in RawImage (Image of what I want) What I have tried so far Unity WebCamTexture API It shows the camera in a texture but it has two problems! It does not record audio and does not have an API to save video! Camera Capture Plugin I bought this plugin but unfortunately it does not have the feature to show video in a texture it just opens the camera device's application. EverPlay plugin I tried this plugin and it seems that it just creates a video from the screen and not the camera Unity Video Capture API There is also this API for recording video with sound but unfortunately it is part of Windows Mixed Reality and does not support iOS Using Objective C I tried to write the video recording section directly in Objective C, I did it but I could not find a way to embed that in the Unity scene I'm not sure it's even possible! ( what I tried) I appreciate any other solutions that can help.
0
Unity using WWW to download image from web. Not working from my own website, but does from other urls I have this script attached to a RawImage file in my games UI public class DownloadImage MonoBehaviour string url "http megabrogames.rf.gd pic.jpg" string url "https i.imgur.com xBSyvRx.jpg" IEnumerator Start () WWW www new WWW(url) yield return www GetComponent lt RawImage gt ().texture www.texture Both jpg files are the same. One I uploaded to Imgur, this works. The other is on my own website. The url to my website works fine, I have checked in on two computers and several browsers. All I get is the red question mark. But if I uncomment the other one instead it all works perfectly. My problem is that I have hard coded the url into the game, and I want to change the image each week. It has to be the same URL for that to work, but i think with Imgur it will auto assign whatever url it feels like. thanks for any help
0
Issue implementing wall jump in Unity I'm having troubles implementing a satisfying wall jump in Unity. I managed to detect collision with a wall, but when I press the jump button, the result is alway weird or very weak. I think this have to do with the 2D physic in Unity, but I have no idead how to handle it correctly. Here's my code with the concerned parts public void Move(float move, bool crouch, bool jump) If the input is moving the player right and the player is facing left... if (move gt 0 amp amp !facingRight) ... flip the player. Flip() Otherwise if the input is moving the player left and the player is facing right... else if (move lt 0 amp amp facingRight) ... flip the player. Flip() if (jump) if (!grounded amp amp walled) StartCoroutine(WallJumpRoutine()) void Flip() Switch the way the player is labelled as facing. facingRight !facingRight Multiply the player's x local scale by 1. Vector3 theScale transform.localScale theScale.x 1 transform.localScale theScale IEnumerator WallJumpRoutine() Vector2 wallJumpVector new Vector2(jumpForce 10, 20f) GetComponent lt Rigidbody2D gt ().AddForce(wallJumpVector, ForceMode2D.Impulse) yield return null To be more precise, the result I'm getting is either my player being moved a tiny bit (despite using the same force as my regular jump, which is working fine) or my player being moved a good distance but at very high speed (this is when I'm using ForceMode2D.Impulse). Any help?
0
Character axis gets messed up when I add the armature into it So basically Ive been working on a walking animation in Blender, but theres a problem when I import it to Unity, the axis get inverted The only thing that is messing it up is the armature that animates the character, if I only import the character itself the axis are normal, if I also import the armature, the axis get inverted...
0
Errors when baking lights in unity3d So, i'm developing a game in unity and avoided baking lightmaps untill now ( i just assembled my new workstation setup wich is capable of baking the lightmaps and not the computer ). And now i have opened my project, imported it nicely and all, went to the lightning tab and clicked generate lightning ( naturallly i had auto bake disabled). And everytime i do that i get a billion errors, and they do not stop popping up even after i force stop amp cancel, i have to clear baking data in order to do anything ( of course unity is laggy as hell when it's spitting out these errors ). I even tried just a simple scene with just a plane on it. It's the same. I checked and it works fine on another empty project, wich lead me to the conclusion that some texture in my assets folder is causing the error even though it's not on the scene at all. In this case i'm kina doomed, i have absolutely 0 idea wich texture could this be ( i have quite a lot of them) and why would it even cause problems. Any way to check that? Or maybe does somebody know another possible reason for this problem? I tried to do research but found literally nothing. No thread about the issue, nothing. Not even the same errors. Thanks in advance. PS i have baked amp realtime GI disabled
0
Cardboard on iPhone 5 doesn't render on stereo Has anyone ran into this? I'm on Unity 5.1.1p3, Cardboard Unity Integration v0.5 (5 28 2015) and an iPhone 5 running iOS 8.3 (12F70). I made a game that uses Cardboard and on an iPhone 6 the screen renders as expected two offset cameras. On an iPhone 5 however, while the screen does show the 2 viewport masking and the distortion correction, it's actually a single camera that is being rendered, defeating the purpose of Cardboard. Here's what I mean. This is the iPhone 6, as expected And this is the iPhone 5, which is wrong Any ideas? Some extra info The iPhone5 can only use GLES2. It doesn't support ES3 or Metal. But what I did notice is that if I make a build for GLES2 the first time the app runs on the device (be it iPhone 6 or 5), when the Cardboard camera gets enabled, the app crashes If then I quit the app and start it again from the phone without it being hooked up to Xcode, on the iPhone5 I get the wrong rendering I've shown while in the iPhone 6 the app just crashes again. And if instead I make my build with automatic graphics API detection, what happens is that on iPhone6 it goes to Metal mode and so it works fine and on the iPhone5 it goes to GLES2 mode which, as stated before, crashes if attached to Xcode but otherwise just runs only that with the wrong rendering.
0
Autonomous robot moving from 1 object to the next object This question falls in line with my last question Unity 3D create autonomous moving robot in house first person camera movement What I have I have a 3D model of a house a first person camera with movement through the house a robot that autonomously moves. What I want I want the autonomously moving robot to search the house for certain objects. I have placed 4 guns (same model) in the house. This is the code I have now. This works for 1 gun not multiple game objects using UnityEngine using System.Collections public class MoveTo MonoBehaviour public Transform goal void Start () NavMeshAgent agent GetComponent lt NavMeshAgent gt () agent.destination goal.position What I want extra If possible, I want it to communicate with the person navigating the "game" with the first person camera. For example, if it finds a gun, I want it to say to the person "playing" the game I found a gun. If it finds the next one I found 2 guns I found 3 guns etc etc. For that, I used the following code for the player using UnityEngine using System.Collections public class UGV MonoBehaviour public Player player assign this variable in the inspector, or using another method public void CallMethodBInPlayer() if(player ! null) player.MethodB() public void MethodA() do something (Robot) And the same for the robot (but changed accordingly). I will be honest with you that I have very little understanding of programming or Unity. I want you to know I've been looking for an answer for many hours but even though the idea might be too complicated for me just yet, I still hope you can (and want) to help me )
0
NavMesh.SamplePosition() fails after rebaking NavMesh? So today I was refurbishing a scene when this happened. After baking a new Navmesh the SamplePosition() returned only infinity. I tried a lot of things out but eventually went back to an older version of my project. Sooner or later I will have to bake a new Navmesh though, so I'd really like to know what happened there. Here is the part of the code that appears to cause trouble Vector3 randomDirection Random.insideUnitSphere roamRadius NavMeshHit hit NavMesh.SamplePosition(randomDirection, out hit, roamRadius, 1) direction hit.position And of course this, since it tries to look into infinity I suppose transform.LookAt(transform.position direction, Vector3.up) Again, this code works fine. Only after baking a Navmesh this fails horribly.
0
In Unity, how can I register a custom file type that is always opened with my game? I want my players to be able to create their own scenes as custom levels, save them as files (say custom1.gamelevel), and open them directly in my game program by double clicking the level file, rather than having to go through the steps of opening the game, browsing to the file in my menus, and then loading that scene level. I already have loading custom levels covered. I just need a way to associate this custom file type with my game which can open it. I am mainly interested in a Windows based solution. How can I do this?