_id
int64
0
49
text
stringlengths
71
4.19k
0
Accessing enum value in other scripts I am attempting to make a global MaterialAssign script that I can assign to anything and have an enum selector in the inspector to assign a material type. This would then drive hitFX and soundFX variation in other scripts. My selector script MaterialAssign.cs using System.Collections using System.Collections.Generic using UnityEngine public class MaterialAssign MonoBehaviour public enum MatSelection defaultMat, metalEnemy, metalWall, dirtWall public static MatSelection currentMat Attempt at usage in another script if (MaterialAssign.currentMat MaterialAssign.MatSelection.metalEnemy) selectedHitFX bulletMetalEnemyFX else if (MaterialAssign.currentMat MaterialAssign.MatSelection.metalWall) selectedHitFX bulletMetalWallFX I have no errors in the console BUT the enum selector doesn't show up in the inspector, so I'm assuming no value is ever passed. I read that enums can't have a static value, but not sure how to handle that. Any assistance would be most appreciated or alternate approaches welcome! I'm purposely trying to stay away from tags, but can go down that path if needed.
0
What causes this z position change? This is a follow up on the following thread. I'm applying a code that will move an object just outside the camera's frustum. I have used the same code in other projects, and it worked fine. However, I'm using it with URP now, and I'm experiencing a z position change while I expected only a x position change. And I just don't see why it does that. I have recorded a video here. If I press the button, the cube should be moved to the left only. But it also moves to the back (z position). And this is the script that I have applied to the cube in the video using System using UnityEngine public class PlaceOutsideCamera MonoBehaviour public void PlaceOutsideFrustum(Transform uTransform, bool uLeft) uTransform.position pPlaceOutsideFrustum(uTransform, uLeft) public static Vector3 pPlaceOutsideFrustum(Transform uTransform, bool uLeft) var frustumPlanes GeometryUtility.CalculateFrustumPlanes(Camera.main) Ray ray Plane plane if (uLeft) 1. ray Camera.main.ScreenPointToRay(new Vector3(0, Camera.main.pixelHeight 2f, 0)) plane frustumPlanes 0 else ray Camera.main.ScreenPointToRay(new Vector3(Camera.main.pixelWidth 1, Camera.main.pixelHeight 2f, 0)) plane frustumPlanes 1 float fDistance Mathf.Abs(Camera.main.transform.position.z uTransform.position.z) 2. var borderPoint ray.GetPoint(fDistance) 3. var frustumOutside plane.normal Bounds b BoundsFromTransform(uTransform) 4. var halfDiameter b.size.magnitude 2f return borderPoint frustumOutside halfDiameter public static Bounds BoundsFromTransform(Transform uTransform) try Bounds bounds new Bounds(uTransform.position, Vector3.zero) wir h tten auch einfach new Bounds() nehmen k nnen, meint Manfredas foreach (Renderer renderer in uTransform.GetComponentsInChildren lt Renderer gt ()) bounds.Encapsulate(renderer.bounds) Vector3 nOff bounds.center uTransform.position return new Bounds(nOff, bounds.size) catch (Exception ex) UnityEngine.Debug.Break() return new Bounds() public void OnGUI() if (GUI.Button(new Rect(0, 350, 100, 50), "DoThis!")) pDoThis() private void pDoThis() this.PlaceOutsideFrustum(this.transform, true) Can anybody tell me why my code does this? I just don't see it. Thank you very much for the help! Edit Here is another video that shows the camera position in the Inspector.
0
Navigating to android app settings permission from unity I am trying to rout from my unity application to android app settings permissions. till now I achieved to rout to app settings, But i want to take 1 step more to go inside permission i mean App Settings Permissions. Code try if UNITY ANDROID using (var unityClass new AndroidJavaClass("com.unity3d.player.UnityPlayer")) using (AndroidJavaObject currentActivityObject unityClass.GetStatic lt AndroidJavaObject gt ("currentActivity")) string packageName currentActivityObject.Call lt string gt ("getPackageName") using (var uriClass new AndroidJavaClass("android.net.Uri")) using (AndroidJavaObject uriObject uriClass.CallStatic lt AndroidJavaObject gt ("fromParts", "package", packageName, null)) using (var intentObject new AndroidJavaObject("android.content.Intent", "android.settings.APPLICATION DETAILS SETTINGS", uriObject)) intentObject.Call lt AndroidJavaObject gt ("addCategory", "android.intent.category.DEFAULT") intentObject.Call lt AndroidJavaObject gt ("setFlags", 0x10000000) currentActivityObject.Call("startActivity", intentObject) endif catch (System.Exception ex) Debug.LogException(ex) Help if it is possible... any help is appropriated. Thank in advance.
0
Why doesn't this weaponpickup script work properly? I'm making an FPS game. My guns are disabled at the start. When I use this script to pick up and hold one weapon at a time, requiring that you click J to drop it, it simply doesnt work! There are two guns using the same pickup script with different prefabs, and all the prefabs but "MyGun" and "playertransform" are the same. using System.Collections using System.Collections.Generic using UnityEngine public class weaponpickup MonoBehaviour public GameObject MyGun public GameObject WeaponOnGround public GameObject DroppedWeapon public Transform playertransform Use this for initialization void Start () MyGun.SetActive(false) Update is called once per frame void Update () if(Input.GetKeyDown(KeyCode.J)) Instantiate(DroppedWeapon, playertransform.position, playertransform.rotation) MyGun.SetActive(false) public void OnTriggerEnter(Collider other) if(other.gameObject.tag "Player" amp amp MyGun.activeInHierarchy false) MyGun.SetActive(true) WeaponOnGround.SetActive(false)
0
2d games unity vs Flash do people find unity better than flash for 2d games while unity is 3d engine , or Flash still better because it's made for 2d games and flash can get the job done faster ,and now flash is better for ios android 2d games . so what platform is the best for 2d games?
0
How can I calculate spotlight lighting in Vertex Fragment shader in Unity? I've written a vertex fragment shader for my game. It uses 3 textures and represents a floating water on the wall (so I have 1 texture for water, 1 for geometry and the last one is mask) so it looks like this But I also need a spot light attached to the camera to lit my geometry, and this is the single dynamic light source on the stage. Well, I can use a surface shader to take dynamic lighting into attention, but I want to avoid using them because it will be much larger and its execution will be much slower. Besides, I need only one dynamic light source, so I can (can I?) just calculate its lighting in the shader, and pass a position direction to the shader using material.SetVector(). It is something like float4 frag(FragmentInput i) COLOR0 float4 col i.col tex2D( Texture, i.uv) col.a tex2D( AlphaMask, i.uv).r 2 if(col.a gt 0.25f) it's water, just return the scrolled texture color float4 l1 tex2D( WaterTexture, float2(i.uv.x, i.uv.y Time.y 16)) float4 l2 tex2D( WaterTexture, float2(i.uv.x, i.uv.y Time.y 8)) return float4((l1 l2).rgb, 0.5f) else it's geometry calculate spot light lighting float lit ... calculations here ... return col lit Is it possible to do this? Will it work faster than the surface shader?
0
Unity camera has no preview, and is not moving I have set up a camera in 2D mode. There is only one camera named "Main Camera", and it is set to "MainCamera" (tag). In console I can see camera's transform position updating, but it isn't moving. And if I adjust field of view for perspective mode, it doesn't take effect. That is saying, when I hit "Play", the game view is always fixed. In inspector there is no camera preview neither (see image 2). The only effect I can make to camera is changing the background color. EDIT Main camera is placed right at root. And the camera is supposed to be looking at a small area EDIT Thanks for DMGreygory pointing out, I'm using default canvas settings and this won't move with camera in play mode. (btw, if not best under canvas, where exactly is suggested to apply those graphics?)
0
Character Movement and Collision with Ragdoll Rigidbodies Colliders? I have a player character that I'm moving with a character controller script and it is moved by applying velocity to a Ridigbody. This works when I have a rigidbody component on the player but my character also has ragdoll colliders and rigidbodies on each body parts (set up with Untiy's ragdoll wizard). What I'd like to do is remove the ridigbody and collider that are on the player and use the ragdoll colliders and rigidbodies instead for physics movement and collision. But it's not working! When I use the rigidbody from the skeleton Root and try to apply velocity the character won't move (animation plays but she keeps running on the same spot). What do I need to do to get this working? Another issue is that if I leave the player rigidbody on but remove the large capsule collider I can move the character but collision doesn't work and she runs through static objects. I already tried with convex set to true on static meshes but it doesn't make a difference. Does somebody know what causes movement and collision not to work with the ragdoll rigidbodies and colliders?
0
Rendering Unity across multiple monitors At the moment I am trying to get unity to run across 2 monitors. I've done some research and know that this is, strictly, possible. There is a workaround where you basically have to fluff your window size in order to get unity to render across both monitors. What I've done is create a new custom screen resolution that takes in the width of both of my monitors, as seen in the following image, its the 3840 x 1080 How ever, when I go to run my unity game exe that size isn't available. All I get is the following My custom size should be at the very bottom, but isn't. Is there something I haven't done, or missed, that will get unity to take in my custom screen size when it comes to running my game through its exe? Oddly enough, inside the unity editor, my custom screen size is picked up and I can have it set to that in my game window Is there something that I have forgotten to do when I build and run the game from the file menu? Has someone ever beaten this issue before?
0
Dragging text element into Text variable unity 4.6 So I was trying to make a UI element to keep score in a unity (4.6) project and I'm having trouble assigning the 'Text' element to the Text variable. So I have the text element with the script attached to it. At the moment the script is empty except from some variables being created, here it is using UnityEngine using UnityEngine.UI public class TextController MonoBehaviour public Text text public int score1, score2 Use this for initialization void Start () Update is called once per frame void Update () text.text "a" "" In the unity UI the Text variable shows but it is empty, and it will not let me drag the 'Text' object from the hierarchy into the variable box. It shows the outline like its going to accept it but remaing 'None (Text)' when I release the click. I tried importing an already working UI from another project into this but when I added it to the hierarchy it removed the text element again (just for reference the text worked perfectly in the other project). Also a screenshot of the hierarch just in case Is there a problem with the scipt or the prject or have I messed something else up? Edit Clicking the circle next to the text variable brings up the window to select the element. Mine shows up without anything in it. I expect it to show the text object I have made.
0
How can I make sure the rotation has finished or the transform is facing the target? void FixedUpdate() LiftProcess() MoveProcess() TiltProcess() if (hasRotate true) Vector3 targetDirection helicopterPlatform.transform.position transform.position Vector3 newDirection Vector3.RotateTowards(transform.forward, targetDirection, lookAtSpeed Time.deltaTime, 0.0f) transform.rotation Quaternion.LookRotation(newDirection) I want ot make a check IF transform.rotation has finished and the transform is facing the newDirection then change the flag hasRotate to false. What check and how should I apply ?
0
Agent trying to reach same position as other agents, instead start spinning in place I create units in my game and have a rally point where they should walk to when created, like Age of Empires. My problem is that since they compete for this position after a while, sometimes they end up doing this https gfycat.com decentquestionableandeancondor https gfycat.com densehonoredgalapagosalbatross As you can see one of the guys cant reach the rally point, so he starts rotating. I realize this has to do with stopping distance, but no matter how high I set the stopping distance this eventually becomes a problem when there are many enough units. And if I set it too high they dont walk to the rally point at all, since its not THAT far from the building they spawn from. Is there any way to manage this scenario? i.e just making him go as close as he can, and then stop? My AI Script using UnityEngine using UnityEngine.AI RequireComponent(typeof(NavMeshAgent)) public class BaseAi MonoBehaviour HideInInspector public NavMeshAgent agent HideInInspector public NavMeshObstacle obstacle float sampleDistance 50 Transform mTransform private void Awake() agent GetComponent lt NavMeshAgent gt () obstacle GetComponent lt NavMeshObstacle gt () mTransform transform private void Start() agent.avoidancePriority Random.Range(agent.avoidancePriority 10, agent.avoidancePriority 10) void LateUpdate() if (agent.isActiveAndEnabled amp amp agent.hasPath) var projected agent.velocity projected.y 0f if (!Mathf.Approximately(projected.sqrMagnitude, 0f)) mTransform.rotation Quaternion.LookRotation(projected) lt summary gt Returns true if the position is a valid pathfinding position. lt summary gt lt param name "position" gt The position to sample. lt param gt public bool SamplePosition(Vector3 point) NavMeshHit hit return NavMesh.SamplePosition(point, out hit, sampleDistance, NavMesh.AllAreas) public bool SetDestination(Vector3 point) if (SamplePosition(point)) agent.SetDestination(point) return true return false public void Teleport(Vector3 point) agent.Warp(point) lt summary gt Return true if agent reached its destination lt summary gt public bool ReachedDestination() if (agent.isActiveAndEnabled amp amp !agent.pathPending) if (agent.remainingDistance lt agent.stoppingDistance) if (!agent.hasPath agent.velocity.sqrMagnitude 0f) return true return false public void ToggleObstacle(bool toggleOn) agent.enabled !toggleOn obstacle.enabled toggleOn void OnDrawGizmos() if (agent null) return if (agent.path null) return Color lGUIColor Gizmos.color Gizmos.color Color.red for (int i 1 i lt agent.path.corners.Length i ) Gizmos.DrawLine(agent.path.corners i 1 , agent.path.corners i )
0
How to handle keyboard controls in Arkanoid game I'm making simple Arkanoid clone in Unity with both keyboard and mouse controls available. When I gave it to my colleagues to test one complain was that keyboard controls are not precise enough,. The problem is that I don't really know how to find a balance between two factors If I make paddle speed too high then it lacks precision to position it just right to make ball go to the last few blocks. If I make paddle speed too slow then it's going to be difficult to reach ball in time. I thought about it and I don't recall any version of arkanoid that solved that problem. Currently I have 3 ideas Make two (or more) keys to go in each direction. One will go faster and another slower. Instead of making multiple buttons lets allow player to change speed of paddle during the game. Probably by entering number from 0 9 on keyboard. Just leave it like it is now. Other control schemes are not intuitive enough. Does anyone have any experience with this? Which approach is the most reasonable? Edit Code I'm using Vector3 pz transform.position pz.y y pz.z 0 if (Input.GetKey(KeyCode.LeftArrow)) pz.x Time.deltaTime KEYBOARD SPEED MULTIP if (Input.GetKey(KeyCode.RightArrow)) pz.x Time.deltaTime KEYBOARD SPEED MULTIP pz.x Mathf.Clamp(pz.x, 60, 60) rb.MovePosition(pz) I simply move paddle by constant speed which includes timedelta. And then I clamp position to screen.
0
Why does the code still working? I was reading an Arduino code regarding counter http www.toddholoubek.com classes pcomp ?page id 58 . Since I do not own a Arduino microcontroller and would like to know the result, I test the concept of the code by using a game object in unity, the void loop() in Arduino function like the void Update in unity. The scale of game object function as if a counter and I tried generate the state 1 or 0 depend on the value of transform.position.y so I can check is it the increment of object scale happen one time only for each transition from state 0 to state 1. For the code below, it worked as intended but when if I transfer this line quot PreviousState CurrentState quot into the if statement quot if ( birdWasLaunched amp amp GetComponent().velocity.magnitude gt 0.1 amp amp transform.position.y gt 1 amp amp CurrentState ! PreviousState) quot , it still working? Been thinking for sometime couldn't see the sense why it still working. As Initially value of previous state current state 0 when transform.position.y lt 1 since the object is launch from a position.y lt 1 upward. After y gt 1 ,value of current state switch from 0 to 1, which made the equality CurrentState! PreviousState become true, then the scale gain 1 increment to its original value. Which is followed by the command line PreviousState CurrentState to made the equality of CurrentState! PreviousState become false in next frame update otherwise object scale increase according to fps. After the object drop to position. y lt 1 due to gravity, the value of CurrentState 0 and PreviousState 1 , I then launch it again upward in y axis direction until position.y gt 1 which the current state become 1 at this time the equality of PreviousState CurrentState at this moment but the scale still get one increment? This is the part where I don't understand. using UnityEngine using UnityEngine.Assertions.Must using UnityEngine.SceneManagement public class Bird MonoBehaviour int CurrentState 0 int PreviousState 0 Vector3 OldPosition Vector3 DistanceDifference float TotalDistance 0 Vector3 initialPosition private bool birdWasLaunched SerializeField private float launchPower 500 void start() OldPosition transform.position private void Awake() initialPosition transform.position void Update() if ( birdWasLaunched amp amp GetComponent lt Rigidbody2D gt ().velocity.magnitude gt 0.1 amp amp transform.position.y gt 1 amp amp CurrentState ! PreviousState) transform.localScale new Vector3(transform.localScale.x 1, transform.localScale.y 1, transform.localScale.z 1) PreviousState CurrentState if ( birdWasLaunched amp amp GetComponent lt Rigidbody2D gt ().velocity.magnitude gt 0.1 amp amp transform.position.y gt 1) CurrentState 1 if ( birdWasLaunched amp amp GetComponent lt Rigidbody2D gt ().velocity.magnitude gt 0.1 amp amp transform.position.y lt 1) CurrentState 0
0
Find References In Scene of scriptable object unity asset shows incorrect results I'm trying to work out why my game is loading a large sprite atlas that I don't think it should be. The snapshot view of the profiler shows that the atlas is loaded. The references pane shows that it's loaded through a scriptable asset object. That object does indeed reference the sprites in the atlas but I don't think the object is referenced in the scene at the moment. The game boots to this scene, so the atlas should not be loaded. I've replicated this profiling on both the editor and on android, so it's not an editor only thing. When I right click on the scriptable object in the project view, while the game is running, and Find References In Scene, it shows a few game objects. None of these objects seem to reference the scriptable object. None even have monobehaviours with fields for this type of scriptable object. Some are new UI button objects, that have Canvas Renderer, Image and Button scripts only. None of which could be referencing this scriptable object. Has anyone seen this behaviour before? What's going on?
0
How to rotate an object around one end of line till its lies on the line From the image below, I would like to rotate a game object C around a point A of a line (made using a line renderer) by an angle d to position p1 till C is on the same line joining points A and B over a given period of time. Preferably using a coroutine. Please note that the angle d is not known. How can I achieve this?
0
Modifying an array of quaternions I have written the following function to inter change 2 specific elements of an array of quaternions private void ChangeRotations(Quaternion rotationsArray) Quaternion bone1Rot rotationsArray (int)Bone1ID Quaternion bone2Rot rotationsArray (int)Bone2ID Quaternion temp bone1Rot bone1Rot bone2Rot bone2Rot temp But when I use Debug.Log to see if this has taken effect, I realize that the 2 array elements are unchanged. What am I doing wrong here?
0
SetActive doesn't work for GameObject I'm using Unity 2D for my game and I'm facing a weird problem. I have a GameObject (an image) in my scene with a button attached to it. When the player is out of the screen, the image that works as a GameOver panel appears and in case of enough coins, you can resume the game. Everything works fine but when the image appears and I click on button to resume, the image doesn't disappear while the function for decreasing number of coins still works. Here is my script in which di() is for die and but() for button using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using CodeStage.AntiCheat.ObscuredTypes using CodeStage.AntiCheat.Detectors public class UIManager2 MonoBehaviour public static ObscuredInt coin score 0 public Text coin text public Slider slider public Slider slider1 public Slider slider2 public GameObject bul public bool reverse public float timer public int delay 1 public float speed 0.5f public GameObject pause public AudioSource aud new AudioSource 3 void Start () coin score ObscuredPrefs.GetInt ("Score") StartCoroutine (elapsed ()) slider1.minValue 0 slider1.maxValue 20 bul GameObject.FindGameObjectWithTag ("Player").GetComponent lt Plane19 gt ().bullet void Update () timer Time.deltaTime if (timer gt delay amp amp reverse false) timer 0f slider2.value if (timer gt delay amp amp reverse true) timer 0f slider2.value speed coin text.text coin score.ToString () ObscuredPrefs.SetInt ("Score", coin score) if (slider2.value 10) bul.SetActive (false) reverse true if (slider2.value 0) bul.SetActive (true) reverse false public void di() pause.SetActive(true) GetComponent lt AudioSource gt ().Pause() Time.timeScale 0 aud 0 .Play() aud 1 .Pause() aud 2 .Pause() public void but() pause.SetActive(false) Time.timeScale 1 aud 0 .Pause() aud 1 .UnPause() aud 2 .UnPause() GetComponent lt AudioSource gt ().UnPause() UIManager2.coin score 2 IEnumerator elapsed () yield return new WaitForSeconds (2f) slider.value StartCoroutine (elapsed ())
0
Using Steering Wheel in Unity Is there any way to use a steering wheel in Unity? All I find online is people with the same problem. The numbering on the axis are not the same as with keyboard input. In some cases left is 1 and as you turn it more to the left it gradually goes down to 0 even though you are still turning left
0
How is this rotation done? There is a video here that shows how the camera rotates around Leon. The camera rotates around Leon in a circle, this is not difficult, but I don't understand the timing logic. Once given a short push, the camera keeps rotating for a few more milliseconds. If the camera would only be rotated during the real mouse movement, the camera would not keep rotating a bit after there is no more mouse movement. However, in this video, the camera rotates a few more milliseconds even after the last mouse movement. How could this be accomplished? Specifically, I would like to ask if somebody can tell me if the developers add some extra movement in the direction of the mouse movement which they then "smooth out", or if they "smooth out" the end of the user's mouse movement. Thank you!
0
How does Unity's Collider.Bounds work? From waht I understand, Collider.Bounds are the sides or bounds of the collider of the GameObject (at least for a cube with a BoxCollider). But I got a result that I wasn't expecting when I tried moving a cube continuously downwards and drawing the bounds with lines. While moving frame by frame, the collider bounds seemed to be not bounding the cube (or at least that's what my test is showing, if my test is correct). Here's 3 frames of screenshot What I did for this is create a new 3D project, add a Cube, then added a single script and then added this script to the Cube. The whole script is using UnityEngine public class NewBehaviourScript MonoBehaviour Vector3 velocity Start is called before the first frame update void Start() velocity Vector3.zero Update is called once per frame void Update() velocity.y 0.5f transform.Translate(velocity) Bounds bounds GetComponent lt Collider gt ().bounds Debug.DrawLine(new Vector3(bounds.min.x, bounds.min.y, bounds.min.z), new Vector3(bounds.max.x, bounds.min.y, bounds.min.z), Color.red) Debug.DrawLine(new Vector3(bounds.max.x, bounds.min.y, bounds.min.z), new Vector3(bounds.max.x, bounds.max.y, bounds.min.z), Color.red) Debug.DrawLine(new Vector3(bounds.max.x, bounds.max.y, bounds.min.z), new Vector3(bounds.min.x, bounds.max.y, bounds.min.z), Color.red) Debug.DrawLine(new Vector3(bounds.min.x, bounds.max.y, bounds.min.z), new Vector3(bounds.min.x, bounds.min.y, bounds.min.z), Color.red) Debug.DrawLine(bounds.min, bounds.max, Color.red) Am I not understanding something or am I doing something wrong?
0
3D infinite platform generation Can't increase space between platforms. (Unity) As seen in the images, changing the value of 'spawnZ' affects the distance between the initial platform and the first generated platform but afterwards it has no affect whatsoever. public GameObject tilePrefabs public float spawnZ 10f public float tilelength public int amnTilesOnScreen 5 public Transform playerTransform Use this for initialization void Start () for (int i 0 i lt amnTilesOnScreen i ) SpawnTile() Update is called once per frame void Update () if(playerTransform.position.z gt (spawnZ amnTilesOnScreen tilelength)) SpawnTile() private void SpawnTile(int prefabIndex 1) GameObject go go Instantiate(tilePrefabs 0 ) as GameObject go.transform.SetParent(transform) go.transform.position Vector3.forward spawnZ spawnZ tilelength
0
Unity 3d auto move player forward script Trying to write a basic script to attach to the player on Unity 3D, I want them to move forward automatically. I'm guessing that will be part of the Update function and using transform, but that's about as far as I get. I'm assuming it's a Transform.translate function too, but not sure what parameters to use to move forward 1 m s automatically (for example). Also, how do I block W and S keys moving forwards and backwards, and instead use the for up and down? (My character is 'floating' and I'm looking to incorporate space harrier style controls) Thank you!
0
How can i detect if the player is inside an explosion radius? I'm making a driving game, there are enemies which spawn on the side of road and when my player car gets close, they fire a rocket in front of the player. I need to detect if the car is within a certain radius of the explosion center. So when I can detect that I'm assuming I can then use rb.AddExplosiveForce to make the car fly a bit or something. What is the recommended way to get the blast radius collider (or equivalent) and detect if the player is inside it?
0
2.5D platformer how to darken building edges? I was wondering how I could go about creating a vignette type effect some sort of volumetric shadow for the 'cross section' parts of a 2.5D level. The effect I'm going for can be seen in 'This war of mine' where the edges of the rooms and walls floors that are facing the camera have been darkened and blurred. (see below). I thought about creating the edges in photoshop and then blurring them and putting them in, however the blur scales weirdly as I'm re scaling the sprites so it looks really fake and not like a visual effect. Is there perhaps a 2d shader I could use or make? Any help on this would be appreciated! Cheers My photoshop attempt to recreate
0
Calculate the starting position of a turning aircraft with inertial force to make it stop at desired position and heading Continued from the answer here, I have some problem when the aircraft in my game has inertial forces after going forward and turning itself. To illustrate, from the following image (https imgur.com a Xvqu2A7) the aircraft is moving from the point A gt B gt C' gt D. I planned to maneuver the aircraft from the point C' which is the point that would make the aircraft stop at the point D after turning with its full performance (using minimum turning radius). The question is how do I calculate the position of the point C' to make the aircraft roughly stop at the point D with the desired position and heading (It is roughly since there is also an inertial force after stopping the aircraft's engine.)? Any suggestions and answers would be appreciated.
0
Sort buttons in unity 2D I've a list of buttons that I create using XML stored data. To achieve it, I've created a Prefab. These buttons are created correctly, and now I want them to be sorted for the user. public List lt GameObject gt myButtons As I said, now I want to sort them. I've found out that sorting the List itself, buttons are sorted in the UI. myButtons.Sort((x, y) gt ...) The problem is, that I don't have the necessary data to sort them within them. This leaves the .Sort() method unavailable for use. I've tried to sort them adding an script to each one, which contains the data that I need to use to sort them. However, it doesn't work correctly and I seem unable to find out why, so I'm wondering about other more direct methods to sort them. Notice that I'm referring to simple buttons in a 2D game, and that they're all inside the same parent gameobject. Technical Details Let's start by the basics I want to order the buttons taking into account if the user has reached a point in which the item it represents should be available. This is stored in an instance of a class that represents the items related to the buttons of the question. public class myItemClass Here there are other properties public bool available Therefore, we've a correspondence between two lists public List lt myItemClass gt myItems public List lt GameObject gt myButtons Where myItems 0 is related represented by myButtons 0 ... NOTICE that this relation exist at the initialization of the game, so i need to keep it at any moment (meaning, having to sort both lists). What I tried To be able to order my buttons depending on if the items are available or not, what I've done is Creating an script myItemScript, which has a reference to my original items from the other list. Sorted the items using Sort function over them. public class myItemScript MonoBehaviour public OtherClass.myItemClass dataObject And then sorting them like myButtons.Sort((x, y) gt y.GetComponent lt myItemScript gt ().dataObject.available.CompareTo(x.GetComponent lt myItemScript gt ().dataObject.available)) As I said before, both list need to be following the same order, so just after it, I order the item list as well myItems.Sort((x, y) gt y.available.CompareTo(x.available)) Checking Debug As result, I found that items were in fact sorting different. However Items inside myItems List were sorted as expected. Buttons in UI (and hence, myButtons List were not sorted as expected. Mixed items (available true false) were mixed and not ordered in two blocks, one first and then the other one. This was checked using breakpoints within VS2017 and pausing the game in Unity interface.
0
How to create a 2D Polygon Sprite from prefab at runtime? At start of my 2D unity game I want to create a new quot building quot (at random). So I created a prefab named quot Building quot from a polygon sprite. Then I created a quot Empty Game Object quot named quot GameManager quot with a script named quot GameManager quot attached to it. The script looks like this public class GameManager MonoBehaviour public GameObject Building Start is called before the first frame update void Start() var createdBuilding Instantiate(Building, new Vector3(0, 0, 0), Quaternion.identity) var sprite createdBuilding.GetComponent lt SpriteRenderer gt ().sprite Vector2 geometry new Vector2 6 geometry 0 new Vector2(0,0) geometry 1 new Vector2(0,20) geometry 2 new Vector2(20,20) geometry 3 new Vector2(27,20) geometry 4 new Vector2(29,29) geometry 5 new Vector2(16,0) sprite.OverrideGeometry(geometry, sprite.triangles) The hardcoded position values are just for testing purporses. The plan is to create multible buildings but first I have to get unity to show at least one of them. Afterwards I attached the prefab quot Building quot to the variable quot Building quot via the inspector. But when I ran the game the sprite is shown as a Pentagon, regardless what I write into the quot geometry quot Array. So why I cant change the geometry? And is this even the right way to create buildings at startup?
0
Unity UI InputField does not consume the keyboard input Unity UI I have an input field in which I can type. Unfortunately, when I hit any of the movement keys, such as the space bar, I move while I'm typing which is not the effect I want. Is there a way to force the input field to consume the keyboard input so it doesn't also get picked up by the game? Or do I have to write the code in my game to do that for me. (Seems like it should be configurable at least).
0
Sprite editor "minimum size" feature alternative in Unity 5 As you know , unity has been removed its minimum size feature in sprite editor multiple auto slice mode. In some pics Unity discovers a lot of tiny rubbish sprites for example as 4x3 or 10x5 pixels. Is there anyway to set minimum size for good auto slicing in Unity 5?
0
Hardcode per instance properties into the shader in unity I am using one of the packages from the asset store and using its Polyline feature for wire rendering. There are thousands of wires and its taking much fps Batch counts. The reason of the lack of support for static batching. Now there is a workaround suggested by the author of the package. if you don't use polylines for anything other than that, and all your shaders use the same properties, you could hardcode all per instance properties into the shader Due to a lack of shader knowledge(I am developing the knowledge currently and it will take time) I am unable to hard code the above properties I tried and here is the current scenario define int ScaleMode 1 define half4 Color (0,0,0,0) define float4 PointStart (0,0,0,0) define float4 PointEnd (0,0,0,0) define half Thickness 0.5 define int ThicknessSpace 1 define half DashSize 1 define half DashOffset 1 define int Alignment 1 HOw do i correctly hard code above values?
0
Ray is not shooting forward This is the code for Raycast RaycastHit hit Vector3 direction transform.forward Debug.DrawRay(transform.position, direction 200f, Color.red, 0.1f) if(Physics.Raycast(transform.position, direction 200f, out hit, 200f)) if(hit.transform.tag "Enemy") do something with enemy I'm shooting the ray to in front of the object, but it's not quite working to me. These are the screenshots As you can see above second picture, shot the ray to forward, but actual ray wasn't forwarded. I also rotated the ray z axis 90 or 90 degree, but stil not working. (Actually I tried to rotate each axis 90 and 90, but nothing seems work) Vector3 direction Quaternion.Euler(0, 0, 90) transform.forward Doesn't work Vector3 direction Quaternion.Euler(0, 0, 90) transform.forward Doesn't work either What am I missing?
0
How to detect a swipe and make the player GO rotate towards the end of the touch Android Unity I am making a game where the user can swipe on the screen and the player gameobject will turn towards the end of the swipe. I am using the following to detect the end of the swipe if (touch.phase TouchPhase.Ended) swipeEndPos touch.position swipeDistance (swipeEndPos swipeStartPos).magnitude if (swipeDistance gt minSwipeDistance) Vector3 swipeEndPoint mainCamera.ScreenToWorldPoint (swipeEndPos) player.Turn (swipeEndPos) And the following to make the player turn towards the end position public void Turn(Vector3 direction) transform.Rotate (new Vector3(0,direction.y,0), Space.Self) Can someone please explain what I am doing wrong? Thank you.
0
How can I create a custom MeshCollider for my object, or fix my collision problem? I have a problem with collisions in Unity and I am unsure how to fix it. I have an octree with a depth of 2, and each node in the tree has a Bounds object attached to it for collisions. I am trying to see which nodes have been intersected by a specific object however it is giving me unexpected results. The colliding object is a flat triangle that I have constructed myself which is acting as a cutting plane and I have attached a MeshCollider component to the GameObject. When there is an intersection with a leaf node in the octree, the node is outlined in yellow and if there is no intersection, it is outlined in purple. Before rotation After rotation In this image I rotated the triangle a small amount on the Y axis and apparently Unity found a collision even though the objects are not even touching at all. I am drawing the octree nodes using Gizmos.DrawWireCube, providing the center and size of the cube which are used to create the Bounds object of the node. Due to this it seems that the Bounds object for the nodes are correct, however the collider for the triangle may be incorrect. When I test this with another 3D object such as a cube, it works perfectly, however not with the object I need it to work with. How can I fix this issue? Collision checking code public bool intersects(Bounds otherBounds) bounds refers to the node's Bounds object otherBounds is the one I'm checking against, in this case the triangle's bounds from the MeshCollider if (otherBounds.Intersects(bounds)) return true return false Octree traversal if (node.intersects(triangleCollider.bounds)) if (node.isLeaf()) node.colour Color.yellow if (node.hasChildren) for (int i 0 i lt node.children.Length i ) findIntersections(node.children i ) It seems that perhaps a quad is being wrapped around the triangle as can be seen in the image below. This image has a triangle which is intersecting the top half of the octree, however the top left octant should have no collision. How can I create a custom MeshCollider which I can specify the vertices manually? See accepted answer for solution int cutterMask 1 lt lt 9 Collider intersectedColliders Physics.OverlapBox(node.bounds.center, node.bounds.extents, Quaternion.identity, cutterMask, QueryTriggerInteraction.UseGlobal)
0
Focus object with specific Rotation in unity C I have different kind of objects with variable dimensions and placed at different position in a scene. I want to focus display each object with the camera with a hard code rotation (north rotation). Like with specific camera rotation I want to focus the object that it completely show to the camera and center of the screen. For this reason, I have write this code snippet that 1 Get the position behind the specific focus object using TransformPoint Provide the elevation using the largest extent of the bound so that it display maximum area of the object. Assign the position and the fixed rotation Vector3 dest destination.transform.TransformPoint(0, 0, behindPositionDistance) GetBehindPosition(destination.transform, behindPositionDistance, elevation) Debug.Log(dest) float eleveMax Mathf.Max(destination.GetComponent lt MeshRenderer gt ().bounds.extents.x, destination.GetComponent lt MeshRenderer gt ().bounds.extents.z) dest new Vector3(dest.x, eleveMax, dest.z) camera.transform.position dest camera.transform.rotation lookNorth But the problem is, it is not accurately working with all objects as every object is at different position and dimension. I want to focus the full object using the camera but without changing the rotation.
0
Unity gizmos with custom renderer Im working on a small project to learn the basics of post processing, shaders and other effects in Unity. My project is in 2D, so I followed this Brackey's tutorial and this tutorial. The bloom effect did not work for me with the expiremental 2D renderer, so I used a forward renderer instead. Problem is, now all of my gizmos (including the camera's gizmos) are gone! Anyone knows what could be the problem? Do I need to set something in the renderer so it will show?
0
C Script file is not showing in Onclick Event in Unity 5.0.4f1? I uploaded the levelLoader file to the gameobject. Still, when I drag the script file onClick Event, the no function is null. Why? Can anybody help me? C code using UnityEngine using System.Collections public class LevelLoader MonoBehaviour Use this for initialization void Start () Update is called once per frame public void LoadLevel(int a) Application.LoadLevel(a) public void Quit() Application.Quit() Correct me where I am wrong. I am following this racing car game tutorial. At 7 58 he added this event. Please help me!!!
0
How to Instantiate enemies (triangles) in the shape of an n sided polygon I am trying to instantiate a cluster of triangles (enemies) in the shape of a polygon and am unsure how to angle them correctly to all be facing away from the center. Thanks to another question, I got the positions roughly right for (int i 0 i lt formation.Count i ) Vector3 pos new Vector3(Mathf.Sin((float)i formation.Count 2 Mathf.PI), Mathf.Cos((float)i formation.Count 2 Mathf.PI)) GameObject tri Instantiate(gameObj, pos, Quaternion.Euler(0, 0, z) , parent) as GameObject Now I just need to get the angles such that all triangles face away from the center.
0
How do I reduce overdraw in a forest scene with lots of foliage? Unity comes with an overdraw view that looks something like this We've probably all seen it, and have probably been advised to check for overdraw. How do you go about actually doing anything about it? My specific case I'm currently seeing a lot of overdraw from my terrain grass and trees as they do not respect occlusion culling. This seems to be a limitation in Unity. Is there anything I could do about it to reduce overdraw without losing the lush environment? For reference, here is the foilage responsible for most of the overdraw and I'm exploring options other than to simply reduce the amount of foliage in the scene and lose the aesthetics
0
(Unity) Is there a way to automatically create a material for each texture and assign the texture to it? I have imported hundreds of textures in my Unity project, and I'd like to create a material for each of them. This would obviously take a lot of time, so how would I go about doing this automatically? These are just basic textures that I want to assign to albedo on the standard Unity 5 shader. No need for normal maps.
0
Render Texture shows opposite view of camera when rendered? I am using render texture (cube) to render what camera sees into it. However, the render texture shows me opposite side of cameras view (flipped) instead of what camera sees. Any solution for this? void Update() renderTexture.isPowerOfTwo true Graphics.SetRenderTarget(renderTexture, 0, CubemapFace.PositiveZ) renderTexture.dimension TextureDimension.Cube camera.RenderToCubemap(renderTexture, 63) What camera sees What Render Texture shows What happens when I rotate Render Texture manually by hand 180 degrees So, instead of rotating per hand, what I want is for the render texture to be rotated via code so that what is in camera view is shown exactly the same in render texture view.
0
Rotate an object with 'Quaternion.Slerp' in world space I'm currently working on a multiplayer skydiving Unity game in which i rotate the players like this transform.rotation Quaternion.Slerp(transform.rotation, desiredRotation, delta) Now this rotates the player relative to it's own rotation. I know rotation in world space is done by multiplying the quaternion of the desired positon with the quaternion of the current position like this localRotation transform.rotation desiredRotation worldRotation desiredRotation transform.rotation But how do i slerp to that position in world space? Thank you all in advance and have a great day!
0
How does Unity Inspector handle values changing during play without any thread locks? First of all, I'm a Java coder. Usually, when you write a game, you run it on thread different than the UI one like pseudocode starts new Thread(new Runnable() Override public void run() while(someVolatileBoolean) input() physics() graphics() and then you declare some sort of listener for the input which usually works on application UI thread so you need to mark it as volatile, atomic or perform a basic synchro using the synchronized keyword (depending on the situation). Let's take a simple Unity script public class SomeMovementScript MonoBehaviour public Vector3 speed new Vector3(0.1f, 0, 0) void Update () this.transform.Translate(speed Time.deltaTime) If we then play the game, the object starts to move with speed 0.1f. Now, when the game is playing, we can change the speed variable through the inspector I thought from the UI coder point of view I'm changing a variable, which is being read each frame by the game thread. How does this happen, that I don't get some sort of ConcurrentModificationException if there's no visible synchronization at all. The variable is public, not being cached in any way. I know that this question should be asked on SO, but I thought that GD has more users specialized in Unity and it's mechanics. I came up with immutability. Variable is considered thread safe if it's state can't change. As components are immutable, and classes like Vector2 3 4 are immutable it would work. But... You can make your own class Serializable , mark their fields as public and the class is not thread safe but it is visible through the inspector. How does Unity Inspector perform these real time updates with all the classes you can think of?
0
How to rotate a parent object while rotating a child object to a certain angle using coroutines I have a semicircle like game object which I made by putting two arcs in an empty game object (SCircle) and rotating the 15 (for left arc) and 15 (for right arc) as seen below. SCircle has an Orientation enum with two valuesLeft (rotates SCircle to 45 ) and Right (rotates SCircle to 45 ) as seen in the image below. I use the following coroutine to move SCircle between orientations. IEnumerator RotateLeftOrRight(Vector3 byAngles, float inTime) Quaternion fromAngle gameObject.transform.rotation Quaternion toAngle Quaternion.Euler (transform.eulerAngles) if (circOrientation Orientation.Left) toAngle Quaternion.Euler (gameObject.transform.eulerAngles byAngles) circOrientation Orientation.Right else if (circOrientation Orientation.Right) toAngle Quaternion.Euler (gameObject.transform.eulerAngles byAngles) circOrientation Orientation.Left for(float t 0f t lt 1f t Time.deltaTime inTime) gameObject.transform.rotation Quaternion.Lerp(fromAngle, toAngle, t) yield return null gameObject.transform.rotation Quaternion.Lerp(fromAngle, toAngle, 1) I also used a very similar coroutine to move the individual arcs by 30 (in opposite directions) from say, Orientation Left, as seen below Since SCircle Coroutine is activated by a mouse click, I have the case where the individual arcs coroutine is run and before it is complete the parent SCircle coroutine is also run. In this case the arcs end up moving from Left to A, which is not the behavior I need. I would want the behavior of them ending up at B when moving from the Left. Likewise, from B, when the SCircle coroutine is run while the arcs coroutine is in progress the orientation will return to the Left. Please note that the blue arrow represents the movement of the left Arc, the red represents the right Arc and the black represents movement of SCircle the parent object. How can I achieve the behavior from Left to B and from B back to Left?
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
Masking cameras for Voronoi splitscreen I would like to mask a camera to only render to a certain (non square) region of the screen, to be used as an overlay, for splitscreen, or any other application. The goal is obviously to prevent any unnecessary rendering from that camera, so I specified performance, but I'm also happy to hear the easiest to implement option as well. What I'm considering so far Stencil shader on a mesh in front of the camera but my understanding is that doing so would require modifying all shaders on world objects, which isn't ideal. Is there an easier way I'm missing? Transparent mesh with a cutout I could cut out a hole in a mesh and the solid part would block rendering of objects behind it, but I'm not sure how to make that part be transparent so other things can render I'm using Unity 2019 LTS and the built in render pipeline I feel like there must be a simple answer I'm missing but maybe I'm wrong?
0
How to set up Easy Mobile Pro to work with assembly defintions? I have a project with EMP imported, and now I would like to use assembly definitions to clean up my project a little bit. Everything works fine in the editor, but when I hit Build player script in my Addressables or just trying to Build I get a bunch of nasty error messages. When I switch to VS obviously there are no issues in the code editor. I have asmdef files in Core folder in my Scripts folder, these are scripts created by myself. asmdef EMP Editor folder this one references 3. asmref EMP Scripts folder asmdef There are the kind of errormessages coming up(when trying to build only, there are 200 of them) Assets Plugins EasyMobile Editor EM BuiltinObjectCreator.cs(6,19) error CS0234 The type or namespace name 'SceneManagement' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) Assets Plugins EasyMobile Editor EM SettingsEditor Privacy.cs(9,24) error CS0234 The type or namespace name 'SerializedProperty' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) Assets Plugins EasyMobile Editor EM SettingsEditor Privacy.cs(10,24) error CS0234 The type or namespace name 'EditorStyles' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) I tried adding a refernece to the Unity.Editor dll in VS to the EMP assembly, but VS just doesn't do anything, no errors, no messages...Tried the same in asmdef file in Unity with no luck... I got the inspiration from this video, and it was working ok... Unity 2019.3 VS 2019 Android platform EMP 2.5.2 Thanks
0
Unity Vertex Color Shader with Transparency I'm trying to achieve a simple effect I have a cube mesh and I want some of the vertices to change color. In this case, I want it to form some sort of a gradient where the unchanged vertices are set to the default color (with alpha 1) and the changed vertices to slowly fade (default color with alpha decreasing towards 0). I'm able to modify these vertices' color with this piece of code using System.Collections using System.Collections.Generic using UnityEngine public class Test MonoBehaviour Mesh mesh Vector3 vertices Color colors List lt int gt verticesToChange void Start() mesh GetComponent lt MeshFilter gt ().mesh vertices mesh.vertices colors new Color vertices.Length verticesToChange new List lt int gt () for(int i 0 i lt vertices.Length i ) colors i Color.white Set the default vertex color if(Mathf.Approximately(vertices i .y, 0.5f)) Change only the vertices on the plane y 0.5 verticesToChange.Add(i) void Update() foreach(int i in verticesToChange) colors i .a Mathf.Max(colors i .a Time.deltaTime 0.5f, 0f) mesh.colors colors Not needed here, but I will be changing the vertices' position too later mesh.RecalculateBounds() mesh.RecalculateNormals() mesh.RecalculateTangents() My problem is selecting a shader that actually uses this color and this color only. I've tried Unlit Color, Unlit Transparent and Particles Standard Unlit with multiple combinations of Rendering Mode, Color Mode and Albedo color. Is there a built in shader that does this and I'm not getting the right combination of its parameters? Or do I have to build my own shader? I've never wrote a shader with Unity, so I would prefer a built in option or an open source free shader.
0
Import Material from blender into unity Export FBX There have been several questions like this but nothing that is quite the same. I've noticed when Mixamo can create models with materials attached in their FBX. I'm trying to do the same in blender, several people say that this cannot be done. When I export an FBX from unity how can I get the material in with it, whether, that be importing the material through a separate process, or some how baking them in with the FBX?
0
Unity Get list of gameobjects close to object clicked? I have a stack of balls of 4 colors some touching some not. When you click on one color ball I want to destroy that ball and any other balls of that color that are close. They may not be touching so collision wont work. How do I detect gameobjects close but not touching that are the same color? Say half a radius away from the edge of the ball clicked. Here are the two scripts I'm working with to create and touch the game objects. public class SpawnBalls MonoBehaviour public Rigidbody ball public float waittime 0.5f Use this for initialization void Start () spawn () Update is called once per frame void Update () Instantiate (ball) public void spawn() yield WaitForSeconds(waittime) for (var i 0 i lt 10 i ) Instantiate (ball) Selecting the balls public class Ball MonoBehaviour public Color colors private Color ballpicked Use this for initialization void Start () GetComponent lt Renderer gt ().material.color colors Random.Range (0, 4) Update is called once per frame void Update () void OnMouseDown() if (Input.GetKey("mouse 0")) ballpicked GetComponent lt Renderer gt ().material.color if (ballpicked "Any other balls within a half a ball width") Destroy (gameObject)
0
My .FBX model is not picking the .TGA texture file I'm at a complete loss. An artist has sent me a 3D model so I can test it in Unity. This is exactly what I got Guy.fbx Guy DIF 512.tga Alright. So I move the folder into the Unity inspector. Suddenly, a Materials folder is created within such folder. The Materials folder has one material. Anyway, now I put the Guy prefab into the scene. It doesn't have textures applied. No problem. A simple Google search yields this response The textures for your model have to be in your Unity project for Unity to apply them automatically when you import. There are 3 different ways to make sure this happens 1 Use Textures for your 3D model from a textures directory already in your Unity project 2 Embed them in the FBX 3 Copy the textures into your project before you import your model I will avoid the second option for now to avoid troubling the artist. Let's see the third option... 3 If you are using 3D software packages that might not have newer FBX plugins or are importing native files you generally do not have the option to embed media, so you will need to copy the textures into a directory inside your project called textures nested next to the model before you import it e.g. Projectx Assets Models Textures ModelTexture.tga Projectx Assets Models Model.fbx Ok, so I created Assets Models Textures and imported the Guy DIF 512.tga file into it. Then in Assets Models folder I import the Guy.fbx file. Doesn't work. The model still doesn't have textures applied. Alright, so let's look at the first option then. ... Let's look at the first option... 1 If you create your textures in your Unity project to start with and source them from a textures directory nested under Models for example, Unity should always create materials and pick up the textures correctly at import Assets Models Textures Assets Models Uh, isn't this the same as the third option? How do I import my 3D model? I am using Unity 5.
0
How to get which gameobject the mouse is over in Unity? So I'm working on a simple drag n drop based trading card game for my own amusement. There is a card inspector included. What I want to achieve is to change values in the inspector (which has its own Inspector.cs, so I would change the variables in it) based on which card I hover over with my mouse. Each card has its own Card.cs attached from which I want to read the values of the current card. If I try to do this from within the Inspector.cs by something like this Name.text gameobject.GetComponent lt Card gt ().Name , then obviously it won't work, because using gameobject in the current context is not valid. So solution No1 would be to properly reference the gameobject over which the mouse is, which I don't know how to do. When I try to do the same from within Card.cs, I cannot use an event trigger OnPointerEnter and run the code through that, because I have to have a reference to the gameobject that contains that function. ( And I cannot do that in a prefab, only in gameobject already existing in the level.) So could anyone tell me how I could achieve what I want, please?
0
2D Platformer Methods to Implement a Whip Weapon I hope posting here isn't a faux pax, if it is please feel free to direct me to the correct location. Or, if there is a thread that already covered this I would love to be pointed in its direction. I've tried looking in quite a few different forums and I can't seem to find very much information about this. What I'm looking to do is implement a whip weapon for a character that's similar to that of Castlevania 4's whip. I have no idea where to start. I'm really just looking for any information. Things like how to program it, the idea of how it was done in the game, really just anything to help me figure out how to make a whip like Castlevania 4. I would appreciate any help. Thank you.
0
How can I implement the traffic( drawing) functionality in the game? I am a beginner game developer. Games such as "Cities Skyline", "Simcity", "Citybounds", and "Traffic lanes 3" directly build roads and show simulations of cars moving over them. I have no knowledge to make these things. I can use Unity, construct2. How can I express things like roads, lanes, intersections, snapping, traffic simulations, path finding, driver AI, traffic lights, even wheels on the road? Road drawing Traffic simulating
0
How to limit the speeding up of enemy movement? Is there a way of limiting my speeding my enemy script every time my player collects 10 points. I have a movement script attached to my enemies and every time my player collects 10 points my enemies get faster. I want to put a limit on that so that the movement script (attached to my enemies) doesn't increase all the time even if the player continue to collect 10 more points and onwards. I want the limit to be 40, so even if the player continues to collect another 10 points the movement should stay at 40. This is my speeding up my enemies script (this is used in my score script) if (Score 10 0) Increment movespeed variable from Movement script Movement.movespeed 4 And this is my movement script attached to my enemies public static int movespeed 20 public Vector3 userDirection Vector3.right public float lifetime void Start () Destroy (gameObject, lifetime) public void Update() transform.Translate (userDirection movespeed Time.deltaTime) How can I limit the movement speed so that it doesn't exceed the upper limit I want?
0
Get world position of touch on objects In my Unity3d game, I want to get the world position that was touched, when I touch a specific object, regardless of all objects that are in front of it. How would I do that, I only know Camera.ScreenPointToRay(...), but for some reason that does not work properly? OK one cannot answer the question with the information I provided. In order to determin the point, where the Ray hit the object, I used RaycastHit.transform.position (which refers to the Transform object that was hit) as opposed to RaycastHit.point (which refers to the Vector3 in world space, where the RaycastHit happened).
0
Creating color texture from greyscale heightmap in shader I'm trying to create a shader that takes a grayscale map as input, and returns a colored albedo that I want to use as texture for my PCG planets, I think that the code below should work, but it only produces flatly white objects. I'm a total shader noob, so I'm terribly sorry if I'm missing something obvious here. Shader "Custom Planet" Properties height("HeightMap", 2D) "white" SubShader Tags "RenderType" "Opaque" LOD 200 CGPROGRAM Physically based Standard lighting model, and enable shadows on all light types pragma surface surf Standard fullforwardshadows Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 struct Input float2 heightMap float minHeight 0 float maxHeight 1 float inverseLerp(float a, float b, float v) return saturate((v a) (b a)) UNITY INSTANCING CBUFFER START(Props) UNITY INSTANCING CBUFFER END void surf (Input IN, inout SurfaceOutputStandard o) float hv inverseLerp(minHeight, maxHeight, IN. heightMap) o.Albedo hv ENDCG FallBack "Diffuse"
0
Slow down in the same time over different distances I'm trying to slow down a object over different distances in the same time, say 3 seconds. My slow down code is. function lerpSpeed (speed float, lerpSpeedTime float) incomingFlightSpeed flightPathScript.flightSpeed i 0 while(i lt 1) i Time.deltaTime lerpSpeedTime i Mathf.Clamp(i, 0, 1) flightPathScript.flightSpeed Mathf.Lerp(incomingFlightSpeed, speed, i) yield So I call it with. waypointScript.lerpSpeed(1,(totaFlighpointsDistance flightSpeed)) In the picture below I've draw a bezier curve and at the last 8 flight points (the red and yellow spheres) I want to start the slow down from the yellow sphere to the last red sphere. I get the distance in between each of the last 8 flight points and total them up to give me the total distance, I understand to get the time it will take to travel that distance is time total distance speed, but as I'm slowing the speed in my function above this will not work. And because every bezier curve I generate is different, some stretched out, with total distances sometimes ranging from 30 to 8. So I'm a bit stuck here, thought I'd get this one, but unless I'm missing something simple I can't get my head around it, so any help would be greatly appreciated, thanks.
0
Get MonoBehaviour components from Prefab I need to assign the script values for the following Prefab in Unity 3.5 The structure is the following Kinect Prefab MonoBehaviour Script Missing Mono Script MonoBehaviour Script Missing Mono Script MonoBehaviour Script Missing Mono Script MonoBehaviour Script Missing Mono Script All the components have the same name. I have tried to obtain all of them in an array, but the GetComponents method does not seem to work properly. var mono MonoBehaviour mono Kinect Prefab.GetComponents(MonoBehaviour) The thing is the resulting array is empty. Any idea what might be wrong? EDIT When I do GetComponents(MonoBehaviour) I get the following error InvalidCastException Cannot cast from source type to destination type. I have tried receiving the components in var mono Component but I still don't receive anything
0
giving to object velocity to the direction it facing (unity) I making 2d game on unity5 .I want to give to an object starting velocity to the direction it is facing(looking).(I put it in the "start" method) how can i do it?
0
How to use the latest MongoDB C driver with Unity? I recently updated my Unity 2018 to the 2020 version then I created a new project to connect my game to a MongoDB database. My main goal is to be able to store not only common data in my collection but also files and images by using GridFS. I use Visual Studio 2019 Community so for my project. I installed the MongoDB drivers directly from NuGet. In Visual Studio everything is OK, I added a using for all required libraries and I have no errors but when I switch to Unity 2020 it seems that I can't start my project because my MongoDB driver is not correctly loaded there. I found some tutorials like this one where they had the same problem and fixing it by adding the DLLs directly in the Unity folders. That works for me, but only with the DLLs shared in the tutorial (you can access the working DLLs in the video description). What is a bit disturbing is that the DLLs' versions seem to be outdated, since the connections process is a bit different from the one in the MongoDB documentation. I cloned the latest MongoDB C driver repository from GitHub and tried to reproduce the same process with the latest DLLs, but once again it only works in VS 2019 but not in Unity, even though I have added the DLLs in the Unity folder. Is there is some kind of compatibility problem between Unity and the latest MongoDB? How can I fix this to work with the latest version?
0
Rigidbody has unintended effect, velocity limiter from unknown source I have made a script that alters a rigidbody's angular velocity. It works well but has one issue, its speed plateaus past a certain point. Here is the script void Start() Get references. bat transform.GetChild (0).gameObject rig bat.GetComponent lt Rigidbody gt () Initialize variables. initPos bat.transform.position initAngle bat.transform.rotation.eulerAngles.y if (leftSide) maxAngle bat.transform.rotation.eulerAngles.y 45 rig.centerOfMass bat.transform.localPosition else maxAngle bat.transform.rotation.eulerAngles.y 45 rig.centerOfMass bat.transform.localPosition void Update() if(leftSide) True and false does the same but mirrored effect. if(Input.GetButton ("Left Bat")) button pressed? if(bat.transform.rotation.eulerAngles.y gt maxAngle) lower than max angle?(since this is the mirrored version, its rot starts at 180 and turns CCW, thus the ' gt ') currAngle 1 turnSpeed then allow turning else otherwise currAngle 0f prevent further turning else button not pressed? if(bat.transform.rotation.eulerAngles.y lt initAngle) greater than resting angle?(same reason as above explanation) currAngle 1 turnSpeed then automatically return else otherwise currAngle 0f stop returning bat.transform.rotation Quaternion.Euler (new Vector3 (bat.transform.rotation.eulerAngles.x, initAngle, bat.transform.rotation.eulerAngles.z)) this statement re aligns the rotation of the flipper its initial state(instantly) to prevent slight kinks due to inconsistencies. bat.transform.position initPos turning the flipper for some reason can deviate its own position(slight but cumulative), this returns the flipper to its initial position. else default version. if(Input.GetButton ("Right Bat")) if(bat.transform.rotation.eulerAngles.y lt maxAngle) currAngle 1 turnSpeed else currAngle 0f else if(bat.transform.rotation.eulerAngles.y gt initAngle) currAngle 1 turnSpeed else currAngle 0f bat.transform.rotation Quaternion.Euler (new Vector3 (bat.transform.rotation.eulerAngles.x, initAngle, bat.transform.rotation.eulerAngles.z)) bat.transform.position initPos void FixedUpdate() rigidbodies should be processed in fixedupdate I think rig.angularVelocity new Vector3( 0, currAngle, 0) The issue is, no matter how high a value I enter for the movement part, it doesn't get faster than a specific speed. I tried hardcoding a value instead of changing the variable but it didn't make a difference. If I enter a small value, the movement is slower though.
0
EventSystem.current is null private void OnEnable() Debug.Log(EventSystem.current) EventSystem.current.SetSelectedGameObject(gameObject) Very simple script for selecting a UI element on enable. However, EventSystem.current prints null to the console. Unity 2019.3.15f1 I have an Rewired event system in the scene. Also tried putting this in an IEnumerator and waiting a frame before logging to the console no change.
0
Is this Possible to force gameobjects (coliders etc) to get stretched based on the aspect ratio of the screen? Well with unity3D, I am in big trouble whenever I use sprites. As for textures I compensate for a evener look by Stretching it (Screen.width amp Screen.height that's fine for low end 2D games). Now If I have an Image and based on content of Image (Let's say I want to add BoxCollider for the walls in image). It works, but for only one aspect ratio. As I am making game for Android. I am having bunch of different resolution amp Aspect ratios. Is this possible to stretch my coliders or other game objects so that I can Work easily???? please help me. I am in a rush (
0
Unity Event Register Deregister and Scene Unload From what I understand in C , normally when you register an event, it maintains a reference to the object of the containing method, so in order for garbage collection to pick up an object, you need to first deregister it. My question In unity when one scene is loaded and another is unloaded, do I need to first clean up and deregister any registered events, or does the scene unload process destroy objects and remaining references?
0
Object pooling in Multiplayer Game. Physics not synchronizing well I implemented object pooling for my multiplayer project. Following Unity Manual I used custom spawn handler for shooting bullets. Bullets game object has rigidbody so selected Sync Rigibody 3D in Network Transfrom. My pool size is 5. While shooting when all 5 projectile is shooted then they have to have to come back to initial position one by one that is the concept of pooling. When projectile moving back they just instantly go back to initial position on host but on client their position are lerping and can easily be seen that we are reusing projectile. How will I fix this ? I've added GIF for better understanding Code For SpawnManager where I'am using Custom SpawnHandler public class SpawnManager MonoBehaviour public int m ObjectPoolSize 10 public GameObject m Prefab public GameObject m Pool private Queue lt GameObject gt objectPool public NetworkHash128 assetId get set public delegate GameObject SpawnDelegate(Vector3 position, NetworkHash128 assetId) public delegate void UnSpawnDelegate(GameObject spawned) void Start() assetId m Prefab.GetComponent lt NetworkIdentity gt ().assetId objectPool new Queue lt GameObject gt () for (int i 0 i lt m ObjectPoolSize i) GameObject obj (GameObject)Instantiate(m Prefab, Vector3.zero, Quaternion.identity) obj.SetActive(false) objectPool.Enqueue(obj) ClientScene.RegisterSpawnHandler(assetId, SpawnObject, UnSpawnObject) public GameObject GetFromPool(Vector3 position) GameObject obj objectPool.Dequeue() obj.transform.position position obj.SetActive(true) objectPool.Enqueue(obj) return obj public GameObject SpawnObject(Vector3 position, NetworkHash128 assetId) return GetFromPool(position) Not calling this function yet public void UnSpawnObject(GameObject spawned) Debug.Log("Re pooling GameObject " spawned.name) spawned.SetActive(false) And this is the code where I am calling these function. public class PlayerTest NetworkBehaviour SpawnManager spawnManager private void Start() spawnManager GameObject.Find("Spawn Manager").GetComponent lt SpawnManager gt () private void Update() if (!isLocalPlayer) return if(Input.GetKeyDown(KeyCode.Space)) CmdFire() Command void CmdFire() Set up prefab on server var prefab spawnManager.GetFromPool(transform.position transform.forward) prefab.GetComponent lt Rigidbody gt ().velocity transform.forward 4 spawn prefab on client and server NetworkServer.Spawn(prefab, spawnManager.assetId)
0
OnRoomConnected always fail (Google play service unity3d) OnRoomConnected always return false, Im stuck...(Authenticate is success). Thank you for attention. private List lt Participant gt participants public void Authenticate() PlayGamesClientConfiguration config new PlayGamesClientConfiguration.Builder() .Build() PlayGamesPlatform.InitializeInstance(config) recommended for debugging PlayGamesPlatform.DebugLogEnabled true Activate the Google Play Games platform PlayGamesPlatform.Activate() Social.localUser.Authenticate((bool success) gt if (success) Debug.Log("Authentication succeeded") CreateQuickGame() else Debug.Log("Authentication failed") ) public void CreateQuickGame() const int MinOpponents 2, MaxOpponents 2 const int GameVariant 0 PlayGamesPlatform.Instance.RealTime.CreateWithInvitationScreen(MinOpponents, MaxOpponents, GameVariant, this) region RealTimeMultiplayerListener implementation public void OnLeftRoom() SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex) public void OnParticipantLeft(Participant participant) SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex) public void OnPeersConnected(string participantIds) Debug.Log("OnPeersConnected") byte message Encoding.ASCII.GetBytes("Test") build your message bool reliable true PlayGamesPlatform.Instance.RealTime.SendMessageToAll(reliable, message) public void OnPeersDisconnected(string participantIds) SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex) public void OnRealTimeMessageReceived(bool isReliable, string senderId, byte data) public void OnRoomConnected(bool success) if (success) Debug.Log("Room Connected success") MainScene ms new MainScene() ms.Waithing sprite.SetActive(true) Successfully connected to room! ...start playing game... PlayersNames 0 participants 0 .DisplayName PlayersNames 1 participants 1 .DisplayName PlayersNames 2 participants 2 .DisplayName GenerateBoard() bool reliability true string data "Instantiate 0 1 2" byte bytedata System.Text.ASCIIEncoding.Default.GetBytes(data) PlayGamesPlatform.Instance.RealTime.SendMessageToAll(reliability, bytedata) else Debug.Log("Room Connected FAIL") PlayGamesPlatform.Instance.RealTime.LeaveRoom() Loading.text "Error!" Back.SetActive(true) Error! ...show error message to user... public void OnInvitation(Invitation invitation, bool shouldAutoAccept) handle the invitation if (shouldAutoAccept) PlayGamesPlatform.Instance.RealTime.AcceptInvitation(invitation.InvitationId, this) else do some other stuff. public void OnRoomSetupProgress(float progress) Debug.Log("Room Progress Waithing players") List lt Participant gt participants PlayGamesPlatform.Instance.RealTime.GetConnectedParticipants() show the default waiting room. if (participants.Count ! 3) PlayGamesPlatform.Instance.RealTime.ShowWaitingRoomUI() Debug.Log("Room Progress Waithing players") else Debug.Log("Room Progress 100") MainScene ms new MainScene() ms.MoveToGame() PlayersNames 0 participants 0 .DisplayName PlayersNames 1 participants 1 .DisplayName PlayersNames 2 participants 2 .DisplayName
0
Unity 5.6 Can no longer select empty GameObject with Gizmo in editor Has anyone else noticed this? I'm using the latest version of Unity (5.6.0p2) and it appears Gizmos are no longer selectable by default. Is there any way to restore this behaviour? Some of my objects are essentially empty (no meshrenderer Filter) with a MonoBehavior attached, which require a gizmo drawn sphere so it can be selected. Is there a better more appropriate way of making non mesh gameobjects selectable in the editor that I'm not aware of? I understand I could use Handles to detect a mouse click but this doesn't allow for simple drag selection (marquee tool) if I want to select a load at once.
0
AI Algorithm to make enemy smarter from level to level in Runner game I am designing a City Runner game in Unity 3D Engine.I am a beginner in game development (not in programming). The idea is really simple, the Runner will be followed by AI enemies, and if caught by one of them it will be dead or his energy will decrease. Anyway I cannot find any Algorithm for implementing a "smart" AI, in the sense that not only he will follow the player and do Path finding to the player, but also get smarter from the first level to the second level. Probably AI must store some information state in regards to the terrain and the runner position. My question here is Is it a good idea to make the AI smarter (because all the runner does is running in a straight line, only the person who is playing the game can change his direction left, right so maybe its not like the learning will be very beneficial) If this is a good idea, do you have any knowledge on what algorithms may be used (implementing neural nets or something alike) If it's not the best idea, what AI mechanism can I use expect of path finding, wandering, seeking, flocking ?? Any kind of advice would be greatly appreciated !! Thank you.
0
How to correctly combine scoreboard data? I need a help with a scoreboard I am making. Here's the scoreboard I want to achieve I actually have 4 tables and each tables has its own scoreboard but for this question only one table matters. Here's how I am creating this kind of scoreboard if (gametable no 1) for (int i 0 i lt tzPlayInfo.Instance.bc gametable history list.Count i ) newString 0 tzPlayInfo.Instance.bc gametable history list i .r newString 0 "," string groupedString newString 0 .Split(',') foreach (string allchars in groupedString) int x 0 int y 0 GameObject o Instantiate(prefab big road 0 ) as GameObject o.transform.SetParent(pos big road 0 ) o.transform.localScale Vector3.one o.transform.localPosition new Vector3(2.0f, 5.0f, 0f) o.transform.localPosition new Vector3(o.transform.localPosition.x x, o.transform.localPosition.y y, o.transform.localPosition.z) if (allchars.Contains(playerwinnopairboth)) o.GetComponent lt UISprite gt ().spriteName "layout player bigline 01" NGUITools.SetActive(o, true) if (allchars.Contains(bankerwinnopairboth)) o.GetComponent lt UISprite gt ().spriteName "layout banker bigline 01" NGUITools.SetActive(o, true) if (allchars.Contains(tienopairboth)) o.GetComponent lt UISprite gt ().spriteName "layout tie bigline 01" NGUITools.SetActive(o, true) The result I get with this code is this Here's what the data I use to generate the table looks like Gametable 1 history P ,P ,P ,B ,B P,P P,TBP So I need a way to know if the character is changing in the gametable 1 history data. Here's the expected scoreboard output with the data above If the value is not changing like P ,P ,P then the position should only increment on the y axis. If the next value is different like B , then it will move on the x axis. So, how would I implement this?
0
How do I stop my first person character going through walls? As per my code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UIElements using Cursor UnityEngine.Cursor public class FirstPersonController MonoBehaviour public float speed 5 public float jumpPower 4 Rigidbody rb CapsuleCollider col private GameObject player private float minClamp 45 private float maxClamp 45 HideInInspector public Vector2 rotation private Vector2 currentLookRot private Vector2 rotationV new Vector2(0,0) public float lookSensitivity 2 public float lookSmoothDamp 0.1f public Camera cam public GameObject crossHair bool isActive Start is called before the first frame update void Start() Cursor.visible false Cursor.lockState CursorLockMode.Locked rb GetComponent lt Rigidbody gt () col GetComponent lt CapsuleCollider gt () player transform.gameObject crossHair GameObject.FindWithTag("CrossHair") Update is called once per frame void Update() float Horizontal Input.GetAxis("Horizontal") speed float Vertical Input.GetAxis("Vertical") speed Horizontal Time.fixedDeltaTime Vertical Time.fixedDeltaTime transform.Translate(Horizontal, 0, Vertical) if (isGrounded() amp amp Input.GetButtonDown("Jump")) rb.AddForce(Vector3.up jumpPower, ForceMode.Impulse) if (Input.GetKeyDown("escape")) Cursor.lockState CursorLockMode.None if (Input.GetButtonDown("Sprint")) speed 15 Debug.Log("Sprint Button Held Down") if (Input.GetButtonUp("Sprint")) speed 5 Debug.Log("Sprint Button Let Go") if (Input.GetKeyDown(KeyCode.H)) isActive !isActive if (isActive) crossHair.SetActive(true) else crossHair.SetActive(false) rotation.y Input.GetAxis("Mouse Y") lookSensitivity rotation.y Mathf.Clamp(rotation.y, minClamp, maxClamp) player.transform.RotateAround(transform.position, Vector3.up, Input.GetAxis("Mouse X") lookSensitivity) currentLookRot.y Mathf.SmoothDamp(currentLookRot.y, rotation.y, ref rotationV.y, lookSmoothDamp) cam.transform.localEulerAngles new Vector3( currentLookRot.y, 0, 0) private bool isGrounded() return Physics.Raycast(transform.position, Vector3.down, col.bounds.extents.y 0.1f) I can't figure out what I am doing wrong in my code, I tried to write a first person controller from scratch. The full project can be downloaded from https github.com Some T FirstPersonController CSharp My player goes through any wall or object easily despite it having colliders on the objects and a rigidbody and collider on the player. I have gone through my code line by line and I cannot work out what is wrong? If someone could please advise me what to change or add to my code to fix this, or and explain the concept, presumably physics related, as to why this is going wrong please?
0
Unsticking game objects I have used void OnCollisionEnter(Collision collision) collision.gameObject.transform.parent gameObject.transform To stick two players together when they connect. Basically after they have collided the second game object is still stuck to the original object and i need that not to be the case. How do i make the game object not stuck when they come apart ?
0
Unity2D coloring a map I have an image with a bunch of colored regions, with each region corresponding to a province in my game. Each province also has a nation owner, which has a respective color. I need to create a function that, when it is called, changes all pixels of a province's color on the first image and changes them to the owners's color on another image. Should I do this with shaders? A script?
0
Trying to make a button in Unity which spawns a character each time it's clicked I have a simple 2D game, I want a UI button to respawn the character (if it's not already present). The first problem I encountered is that the button only works once. I can't go any further before I solve this, so for now it doesn't spawn anything, I just want it to print debug text every time it's clicked. It only does that once, unfortunately. How do I make it call the function each time I click it? using UnityEngine using System.Collections using UnityEngine.EventSystems public class Button Restart MonoBehaviour public Canvas Canvas void Awake() public void Restart() Debug.Log("Restart button was clicked") EventSystem.current.SetSelectedGameObject(null)
0
In unity 5 export package is not working correctly I am using unity 5. I Created an objects with layer names. I tried to export a package. After Exporting, i import the package in new project and ran the project its not working. observed that objects layer name is missing for all the objects. i attached the screenshot with this. Before Export After Import the Exported Package In layer drop down box no layer name was found. only the default layer name is available. if anyone knows the answer please tell me.
0
Performance of manipulating a mesh in realtime Does Unity allow streaming mesh data that can be continuously changed? I have a level that is dynamically changing based on some parameters. The number of triangles stays the same, they just change positions. I'm speaking of around 2000 triangles that need their position updated each frame (they follow a spline that is computed on CPU), running on mobile phones. I can't use a TrailRenderer because the object is a whole level. I can't use bones, because I need to know the final position for each vertex for my custom collision code. The mesh should be marked Mesh.MarkDynamic.
0
How can i make all the scene dark night and spot a light on specific place area in the scene? I want to light the area of the 5 spheres. All the rest to be dark. What i have in the Hierarchy is Directional Light. I'm not sure if i need other lights objects and what to do to make it dark night environment and how to spot a light on the specific area.
0
How do I dynamically load a smaller texture in Unity based on the screen size? I have a Unity application on windows phone which is having problems running on small devices because the HD textures are so huge. What is the best way to test and dynamically use a smaller version on a smaller or less powerful device?
0
Addressable Asset Loading with Queue And Coroutine I have around 17000 addressable assets (prefab) tiles that I am loading near the position of the camera. Here is my algorithm Get all Reference of the 17000 tiles in the array Loop through the array and get the tiles that are within the proximity of my Player and queue It. Based on the first enqueue item, start downloading the tiles with Addreessabl.Instantiate. Load one by one and wait for the first item download to finish. here is the main loop that is doing the work public IEnumerator StartDownloading() isDownloadStarted true while (singleAbLoader.Count gt 0) SingleADLoader singleAbLoaderCurrent singleAdLoader.Dequeue() if (abLoaderUnloaderManager.GetTilesWithinPlayerRange(singleAbLoaderCurrent) true) Debug.Log( quot Starting to call quot singleAbLoaderCurrent.gameObject.name) yield return singleAbLoaderCurrent.DownloadAB() Debug.Log( quot Finsihed to call quot singleAbLoaderCurrent.gameObject.name) loadingSlider.value sliderIncrementValue else Debug.Log( quot escaping the download quot singleAbLoaderCurrent.name) yield return null isDownloadStarted false whereas the DownloadAD() public IEnumerator DownloadAD() AsyncOperationHandle lt GameObject gt handle Addressables.InstantiateAsync(prefabToLoad) yield return handle The tiles are loading fine but the problem is they are way too slow. I mean it takes much time to load tile.
0
OnMouseClick not detected I created "main script" and in Start() created simple cube GameObject cube GameObject.CreatePrimitive(PrimitiveType.Cube) cube.transform.localScale new Vector3 (1,2,1) cube.GetComponent lt Renderer gt ().material.color new Color(0,0,255) cube.AddComponent lt CubeScript gt () and then in CubeScript I have empty Start() and Update() but in onMouseDown() just Debug.Log("click detected") and I can never see log despite clicking on cube.. Any advice? did I missed something?
0
Periodic updates of an object in Unity I'm trying to make a collider appear every 1 second. But I can't get the code right. I tried enabling the collider in the Update function and putting a yield to make it update every second or so. But it's not working (it gives me an error Update() cannot be a coroutine.) How would I fix this? Would I need a timer system to toggle the collider? var waitTime float 1 var trigger boolean false function Update () if(!trigger) collider.enabled false yield WaitForSeconds(waitTime) if(trigger) collider.enabled true yield WaitForSeconds(waitTime)
0
Add action to GameObject So I'm creating a Unity project that has a bunch of buttons (like hundreds) that each do a different thing when pressed. This is a 3D project and these buttons are also 3D. I already know how to detect if the player has pressed a button, so I just need to know how to attach an action to one of these buttons. Should I create a script for each? From what I've found, it's very memory expensive and will definitely drop FPS especially for hundreds of buttons. Should I try to use a UnityEvent? I don't know if this helps for what I'm doing...?
0
Circle Collider Vibrates on Edge Collider I am making a game (kind of bricks) and using edge collider objects as world bounds collider. I am increasing count of balls on each iteration, after 5 balls, balls start to vibrate when they contact with edge colliders. Vibrating means, they do not bounce directly when they contact with edge collider, they vibrate on x axis for some period while they are moving upwards on y axis. Ball physics (friction is 0, bounciness is 1) Wall physics (friction is 0, bounciness is 0) I am not updating transform of ball object, directly set a velocity to balls. Also i've recorded a video for this behavior https www.youtube.com watch?v K bjkXZjXjs amp feature emb logo Which point i am missing on this setup? Can you help me to solve this problem? Best, Edit I have a input listener class, that updates BallThrowHandler.thrown variable, when you put your finger to screen, move and release. Code that adds velocity to balls (which is running on another object) using UnityEngine using System.Collections public class BallContainerBehaviour MonoBehaviour lt summary gt total speed of the balls lt summary gt public float totalSpeed 5f public float timeBetweenBalls 0.2f WaitForSeconds wait public float degrees 0f Rigidbody2D childBody Vector3 speedVector float cosinus float sinus void Start() wait new WaitForSeconds(timeBetweenBalls) void Update() if(BallThrowHandler.thrown) start throw animation startBallMovement() start ball movement if they thrown private void startBallMovement() calculateDegrees() speedUpBalls() if(BallThrowHandler.thrown) StartCoroutine("speedUpBalls") CollectBallHandler.CollectingBallsStarted false BallThrowHandler.BricksMovedDown false private void calculateDegrees() degrees Vector3.Angle(Vector3.right, BallThrowHandler.ThrowVector) Mathf.Deg2Rad private IEnumerator speedUpBalls() cosinus Mathf.Cos(degrees) sinus Mathf.Sin(degrees) speedVector new Vector3(totalSpeed cosinus, totalSpeed sinus, 0f) foreach (Transform go in transform) childBody go.gameObject.GetComponent lt Rigidbody2D gt () childBody.velocity speedVector yield return wait BallThrowHandler.thrown false And here is whole code for a ball object (only bottom collider is trigger, left right and top is not) using UnityEngine using System.Collections public class BallEndTurnBehaviour MonoBehaviour Rigidbody2D body public float ballMinY public GameObject bricksContainer private BrickSpawner brickSpawner private BrickTurnOverMover brickTurnOverMover private const float EPSILON 0.01f private void Awake() body GetComponent lt Rigidbody2D gt () void Start() brickSpawner bricksContainer.GetComponent lt BrickSpawner gt () brickTurnOverMover bricksContainer.GetComponent lt BrickTurnOverMover gt () private void Update() if(System.Math.Abs(body.velocity.x) lt EPSILON amp amp System.Math.Abs(body.velocity.y) lt EPSILON amp amp CollectBallHandler.CollectingBallsStarted) transform.position Vector3.Lerp(transform.position, CollectBallHandler.CollectingBallsPoint, 0.1f) private void OnTriggerEnter2D(Collider2D collision) if (!CollectBallHandler.CollectingBallsStarted) CollectBallHandler.CollectingBallsStarted true CollectBallHandler.CollectingBallsPoint transform.position CollectBallHandler.CollectingBallsPoint.y ballMinY body.velocity new Vector3(0, 0, 0) Vector3.Lerp(transform.position, CollectBallHandler.CollectingBallsPoint, 1f) if(!BallThrowHandler.BricksMovedDown) brickTurnOverMover.moveBricks() BallThrowHandler.BricksMovedDown true brickSpawner.spawn()
0
Creating a random lottery system I would like the game to give all 16 characters (15 NPC 1 player) a number 1 16. This number stays the same no matter what and is unique only to that character so two characters cannot have the same number. At a point in the game, the character presses a button. I need this button to generate a random number and load a scene based on the number. Example Player's pre determined number is "8", if the number generator generates an "8" as well, it would load the next scene (where the player has to run away from a mob) If the generator generates anything else other than "8" It will load a different scene (where the player chases an NPC) Just to clear it up if the number generator generates 1 7 or 9 16 it will load the same scene no matter what. (Getting "9" from the generator would load the same scene as "2" would. Only when "8" is generated, would there be a separate scene) I'm still incredibly new to Unity and coding in general, so a brief summary of what each line of code is doing would be majorly appreciated! (but not at all demanded!) I'm most comfortable with C so if you could have the code in that would be great!
0
How to best apply colliders on a rough 3D shape I have a 3D model for a level in unity. I want to add colliders to it. What is the best type of collider for this model? And,it is 3D
0
Unity3d FullScreen Mode Vertical Aspect Ratio in WebGl My game has vertical aspect ratio and looks like this When I press full screen button lt div class quot webgl content quot gt lt div id quot gameContainer quot style quot width 500px height 860px quot gt lt div gt lt div gt lt div class quot fullscreen quot onclick quot gameInstance.SetFullscreen(1) quot gt lt div gt My game start to look like this I need to save aspect ratio of the game how can I do that?
0
Rotate Rigidbody to face away from camera with AddTorque I have a camera that rotates around an object with "Look At" . I want the object to rotate to face the direction the camera is pointing (Camera.main.transform.forward) using AddTorque, but I can't understand how. I tried to create a rotation in which the more the object's forward vector rotates towards the camera, the more it should slow down the rotation until it stops. But it only works in sections, when I use the rotation of the camera the object rotates and then stops, as if it detects only one part of the rotation, while the other is a blind spot. What equation can I use to rotate the object well? var currentR rb.rotation.y var targetR Camera.main.transform.rotation.y rb.AddTorque(transform.up 1000f (targetR currentR)) DMGregory I put your script as it is in a separate new script on a new object, equipped with a rigidbody. I post the script how I entered it. At "targetOrientation" I gave the value of "Quaternion.LookRotation (Camera.main.transform.forward) " because I want the object to follow the direction of that camera. The result is that all the axes of the rigidbody are influenced by the rotation (if I lift the camera the object turns towards the ground, etc.), and above all that the rotation works even if I block the axes with Freeze Rotation, and with this script the object is no longer affected by external forces. public class rotation MonoBehaviour private Rigidbody rb public Transform direction Start is called before the first frame update void Start() rb GetComponent lt Rigidbody gt () Update is called once per frame void Update() Quaternion targetOrientation Quaternion.LookRotation(Camera.main.transform.forward) Quaternion rotationChange targetOrientation Quaternion.Inverse(rb.rotation) rotationChange.ToAngleAxis(out float angle, out Vector3 axis) if (angle gt 180f) angle 360f if (Mathf.Approximately(angle, 0)) rb.angularVelocity Vector3.zero return angle Mathf.Deg2Rad var targetAngularVelocity axis angle Time.deltaTime float catchUp 1.0f targetAngularVelocity catchUp rb.AddTorque(targetAngularVelocity rb.angularVelocity, ForceMode.VelocityChange) I set a command if (Input.GetKeyDown (KeyCode.T)) rb.AddTorque (transform.up 5500f, ForceMode.Impulse) to rotate the object with an impulse and this does not work when your rotation script is active. I also place a video where you see the object before activating the rotation script, and after it is active, to see how it does not react to the impulse with T, and how it rotates reacting on all rotation axes, while I want only that the rigidbody only rotates its Y axis of rotation, in the direction of the camera (as a person does when turning in one direction). In the video The axes of rotation X and Z are on freeze (otherwise without fixed the rotation the object falls moving). I also put a video of the desired effect taken from a game so as to explain me better. My video desired rotation
0
Unity UI InputField does not consume the keyboard input Unity UI I have an input field in which I can type. Unfortunately, when I hit any of the movement keys, such as the space bar, I move while I'm typing which is not the effect I want. Is there a way to force the input field to consume the keyboard input so it doesn't also get picked up by the game? Or do I have to write the code in my game to do that for me. (Seems like it should be configurable at least).
0
differing methods of Instantiating GameObjects in Unity (what is the difference?) I have been using Unity a while and always Instantiated objects slightly differently from what many of the tutorials and posts online say (I've seen 3 very similar ways). It seems to have the same outcome much of the time, however now I am trying to instantiate the prefab using my "Resources" folder instead of dragging it from the inspector and on one method it said it was an 'object' not 'gameobject'. I can't really find anything on Unity website or here, so what is the difference between the following These two lines to me seem identical, but most tutorials dont cast, and rather use the latter of the two instead, why? currentBall (GameObject)Instantiate(Resources.Load(prefabName, typeof(GameObject))) currentBall Instantiate(Resources.Load(prefabName, typeof(GameObject))) as GameObject This one I know is different somehow, because Unity said cannot convert from Object to GameObject, but honestly i do not understand why currentBall GameObject.Instantiate(Resources.Load(prefabName, typeof(GameObject)))
0
How can I draw a specific GameObject into a texture in Unity? I need to draw only a few specific objects into a texture (with their material) and then use that RenderTexture as a texture for an another object. I think Graphics.DrawMesh() and Graphics.SetRenderTarget() would be helpful, but I'm not sure. Ultimately I'm trying to create refractive water, which will refract only specified GameObjects, not layers. How can I do this?
0
Unity IUnityLifecycleManager already exists I followed this tutorial https www.youtube.com watch?v OElh7wda4Qc in Unity version 2019.3.1f.1 Personal Edition, but I got 6 errors like this in the console, also I updated to version 3.4.4 via the package manager, because it said that the asset store version was not compatible anymore. Library PackageCache com.unity.ads 3.4.4 Runtime Monetization AndroidPlacementContentOperations.cs(55,40) error CS0433 The type 'IUnityLifecycleManager' exists in both 'UnityEngine.Advertisements.Editor, Version 3.4.2.0, Culture neutral, PublicKeyToken null' and 'UnityEngine.Advertisements, Version 3.4.2.0, Culture neutral, PublicKeyToken null' This is the code I am using, its the same as the code in the official website, but personalized to my project. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Advertisements using UnityEngine.UI public class adsController MonoBehaviour, IUnityAdsListener public bool testMode true public Button rewardedAd private string storeID "3509232" private string rewardedVideo "rewardedVideo" private void Start() rewardedAd.interactable Advertisement.IsReady(rewardedVideo) rewardedAd.onClick.AddListener(ShowRewardedVideo) Advertisement.Initialize(storeID, testMode) private void Update() private void ShowRewardedVideo() Advertisement.Show(rewardedVideo) Implement IUnityAdsListener interface methods public void OnUnityAdsReady(string placementId) If the ready Placement is rewarded, activate the button if (placementId rewardedVideo) rewardedAd.interactable true public void OnUnityAdsDidFinish(string placementId, ShowResult showResult) Define conditional logic for each ad completion status if (showResult ShowResult.Finished) Reward the user for watching the ad to completion. Debug.Log("Reward") else if (showResult ShowResult.Skipped) Do not reward the user for skipping the ad. Debug.Log("Not Reward") else if (showResult ShowResult.Failed) Debug.LogWarning("The ad did not finish due to an error.") public void OnUnityAdsDidError(string message) Log the error. public void OnUnityAdsDidStart(string placementId) Optional actions to take when the end users triggers an ad. EDIT Looks like I forgot a line in the code and reinstalling the unity ads package now it runs but still gives this warning. Please consider upgrading to the Packman Distribution of the Unity Ads SDK. The Asset Store distribution will not longer be supported after Unity 2018.3
0
Can I add rigging bones to a model imported from Blender inside Unity? I created a model in Blender but recently I stumbled upon a video claiming that you can add rigging to a model in Unity. So instead of rigging in Blender, is it possible to do it in Unity?
0
Creating a random lottery system I would like the game to give all 16 characters (15 NPC 1 player) a number 1 16. This number stays the same no matter what and is unique only to that character so two characters cannot have the same number. At a point in the game, the character presses a button. I need this button to generate a random number and load a scene based on the number. Example Player's pre determined number is "8", if the number generator generates an "8" as well, it would load the next scene (where the player has to run away from a mob) If the generator generates anything else other than "8" It will load a different scene (where the player chases an NPC) Just to clear it up if the number generator generates 1 7 or 9 16 it will load the same scene no matter what. (Getting "9" from the generator would load the same scene as "2" would. Only when "8" is generated, would there be a separate scene) I'm still incredibly new to Unity and coding in general, so a brief summary of what each line of code is doing would be majorly appreciated! (but not at all demanded!) I'm most comfortable with C so if you could have the code in that would be great!
0
Best Practices for Locating Clicks I am building a 2D board game in Unity with a static camera pointed down at the game board. During the active phase of each player's turn, I want to detect where they click on the board. Fortunately, the board is laid out in an easy rectangular grid. (Essentially a trio of 5x5 grids). Which of the following would be best practice to implement this? Create invisible colliders for every square on the board and create a translation function that translates those back to board positions (5,3) with Raytracing? Get the translated coordinates of the click and use a function to figure out which square (if any) the click is in using the mouseclick event handler (by calculating which square the grid coordinates fall in)? Make each square a button with its grid identity encoded and use that in its OnPressed function? Edit 4) Some other idea I haven't thought of yet? Experience level I'm just learning Unity, but have written a lot of C (and tons of other code).
0
Recommend a way to draw thousands of particles (liquid) per frame in Unity3d I'm writing a plugin for this library for Unity3d. I have it working and now I am looking for an efficient way to draw the particles. My 1st test just uses sprites and runs fine on my laptop but I doubt it will be so good on a mobile device. Is there a cheap way of simply drawing lots of particles to the screen each frame? The library generates an array of all the particle positions which updates in FixedUpdate() so I can just draw everything in that array each frame. I'm thinking maybe somehting in the Graphics namespace would handy here, like maybe Graphics.DrawTexture Also I might consider doing some kind of metaballs like pass over the particles to make them look more liquid like.
0
World space UI stretched too much instead of billboard in unity I am scaling my world space UI element as my camera go far away from UI using this code snippet public class ZoomNamePlace MonoBehaviour public CameraController camContrller public int Zoom Factor void LateUpdate() Zoom() void Zoom() float size (Camera.main.transform.position transform.position).magnitude It is working fine and my UI scale according to the distance of Camera and UI. Now i want to rotate billboard my world space UI to the camera and here is my script public class Billboard MonoBehaviour Orient the camera after all movement is completed this frame to avoid jittering void LateUpdate() Camera m Camera Camera.main transform.LookAt(transform.position m Camera.transform.rotation Vector3.forward, m Camera.transform.rotation Vector3.up) But the problem is instead of billboard my UI shape stretched too much maybe due to my canvas scale set to 0.01.
0
Can I use Unity remote with a Android emulator instead of Android phone? Unity Remote is good app. It allows to connect with Unity while you are running your project in Play mode from the editor. But what if I want to test game but I don't have an Android phone? Yes, it happens ( ) I have a great Android emulator Nox APP Player The emulator doesn't have USB, so it just show me standsrt text Connect device with a USB cable ..... bla bla bla ...Game in the Unity Editor is running...emulator doesn't display the game. Can I somehow connect this emulator to unity using Unity Remote? Or using something else? How?
0
How do I find more details about a Vuforia error when going into play mode? I want to make an AR app in Unity using Vuforia Engine. But when I try to enter play mode nothing appeared. Here's the error alert Since this error does not give me any clue about what went wrong, I'd like to know if there is a way to get more details about it so I can eventually figure out how to fix it.
0
Passing Gameobject to another script in unity 3d I'm trying to pass a gameobject from one script to another runtime attached script. My fisrt script is attached to the FirstPlayerController and the gameobject is not dragged in the editor, but is picked up and carried in the script. All i want is to pass the gameobject to the CameraController class to as make the second camera follow that object. Below is what i've tried so far. I dont want to access the gameobject with the tag, because there are more gameobjects that can be picked up. I want to access the carried object to the cameracontroller class. Thanks! Pickupobject.cs using System using System.Collections using System.Collections.Generic using UnityEngine public class pickupobject MonoBehaviour GameObject mainCamera bool carrying public GameObject carriedObject public float distances public float smooth float speed 1000f new Camera camera Use this for initialization void Start() mainCamera GameObject.FindWithTag("MainCamera") camera GameObject.FindWithTag("secondCamera").GetComponent lt Camera gt () camera.enabled false Update is called once per frame void Update() if (Input.GetKeyDown(KeyCode.T) amp amp carrying) carrying !carrying ThrowBall() if (carrying) carry(carriedObject) else pickup() private void pickup() if (Input.GetKeyDown(KeyCode.E)) int x Screen.width 2 int y Screen.height 2 Ray ray mainCamera.GetComponent lt Camera gt ().ScreenPointToRay(new Vector3(x, y)) RaycastHit hit if (Physics.Raycast(ray, out hit)) pickupable p hit.collider.GetComponent lt pickupable gt () if (p ! null) carrying true carriedObject p.gameObject camera.enabled true camera.gameObject.AddComponent lt CameraController gt () carriedObject.AddComponent lt MovingBall gt () void carry(GameObject o) o.GetComponent lt Rigidbody gt ().isKinematic true o.transform.position mainCamera.transform.position mainCamera.transform.forward distances void CheckDrop() if (Input.GetKeyDown(KeyCode.U)) Drop() void Drop() ThrowBall() void ThrowBall() mainCamera.SetActive(false) camera.enabled true carriedObject.AddComponent lt CameraController gt () camera.gameObject.AddComponent lt CameraController gt () carriedObject.AddComponent lt MovingBall gt () carriedObject.GetComponent lt Rigidbody gt ().isKinematic false carriedObject.GetComponent lt Rigidbody gt ().AddForce(0f, 0f, speed) CameraController.cs using System.Collections using System.Collections.Generic using UnityEngine public class CameraController MonoBehaviour public GameObject icosphere public GameObject abc Vector3 offset Use this for initialization void Start () icosphere GameObject.FindWithTag("purpleball") offset transform.position icosphere.transform.position Update is called once per frame void Update () transform.position icosphere.transform.position offset
0
Can not tweak collider s border manually in Unity Why can not I change collider s border manually? I remember being able to do that. I just clicked the gray button under in this case Box Collider 2D component, then went to the Scene view and tweaked it as I wanted by clicking and moving collider s border. But now when I do the same procedure on trying to click and drag the border in Scene view I am just losing focus of the collider, but do not change it in any way.