#archived-code-general
1 messages · Page 406 of 1
but only like 5 different types so the switch statement will have 5 items
anyone?
is a pistol genuinely that different from a rifle?
no but my inventory is going to have a slot for every weapon type ie one for pistols one for riles one for shotguns one for smgs one for projectiles
what is offset?
(the offset variable just puts it infront of the camera)
just a vector for how far infront of the camera i want them to be
in this case its (0,0,1)
then the concept of a "slots" should be defined differently per weapon
Shouldn't that depend on your rotation?
instead of being world +Z
That's quite a lot.. maybe consider using inheritance if you're not certain as well. You'll be able to add more without having to constantly modifying working scripts (potentially creating more bugs). It's more difficult to imagine (relative to complexity) but can isolate new modifications or reduce the need to modify already working behaviors.. which can improve the debugging process.
fair point, how would i make it relative to my current rotation in that case?
I'll give it a go, thanks
You dont have to use inheritance to add more weapons without editing code but I guess since everyone here is suggesting it is what is the "right" way to do this.
if its scriptable objects each "gun" can be a new so with different settings
do whatever as long as its not weird switch statement hell
You've ask, folks have critiqued. There isn't a "right" way but having a large switch (that's to be modified on adding more guns) is less manageable imo
Every kind of gun does roughly the same thing: fire zero or more of some kind of projectile at some rate.
Hence why I mentioned this
If that's only needed so you can put the weapons into different categories, then an enum is okay (I'd prefer a WeaponClass scriptable object, though!)
public enum WeaponSlot
{
Fist,
Melee,
Handgun,
SMG,
Shotgun,
AssaultRifle,
Rifle,
MachineGun,
Heavy,
Projectile
}
public enum WeaponType
{
Melee,
Gun,
Projectile
}
public class Weapon : ScriptableObject
{
public string displayName;
public WeaponSlot slot;
public WeaponType type;
public float dmg;
public float rate;
public int animationLayerID;
}
public class WeaponManager
{
private Weapon currentWeapon;
public void ExecuteUse()
{
switch (currentWeapon.type)
{
case WeaponType.Melee:
MeleeLogic();
break;
case WeaponType.Gun:
GunLogic();
break;
case WeaponType.Projectile://Grenades etc
ProjectileLogic();
break;
}
}
This was my original plan
you could then put a name, description, and icon into that WeaponClass asset
See why not give Weapon public abstract void DoLogic() and call that 😐
you can add guns all day and dont need to change code
for what reason?
there are 3 weapon types
not 30
WeaponManager doesnt need to know what the weapon does, only needs to know how to tell any weapon to execute its stuff
If you have fundamentally different kinds of weapons, that's where different types start making sense
Looks manageable - fair enough.
OOP isn't as necessary as a lot of folks make it out to be.
didn't seem to fix it unfortunatley
If its just you and you know whats going to happen in future then so be it.
Its not good when others need to maintain something in future. I have needed to refactor some "strange" code and that takes extra time, effort and creates bugs.
show me the entire script after making those changes
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
what is "followTarget", anyway?
does that represent the player?
or is it the player's controller?
follow target is the camera's position. this is what my hierarchy looks like
okay, so the target position is:
- the position of your hand (from
actions["Position"]) -- I think that's measured relative to the VR player's playspace? - the world space position of the camera
- the offset, which pushes it forwards away from the camera
I suspect the first one is the issue
the actions["Position"] is relative to the XR origin, which is essentially the centre of your playspace, yeah.
How are you rotating?
are you physically turning around in your room here?
wait, silly question
you are not doing a barrel roll lmao
lol
That's going to be your problem.
I'm rotating with AddTorque() on the player's rigidbody
You need to transform that position into world space (correctly including how the player has been moved, rotated, and scaled)
hmm...I'm actually not quite sure what to do about that
Are you using unity 6 for xr rotation.
Yeah, all this stuff messes with my brain
I'm on unity 6 yeah
Actually, if you're moving the entire XR origin around in game, then it's simple
transform your position with it
whatever.TransformPoint(inputPosition);
It gives odd results like that try using unity 2022
i don't think that's very useful advice
I believe the XR origin always remains at (0,0,0). the player is what's moving in the scene
I guess you could just transform the point with the player's transform, then
That will turn it from a local-space point for the Player to a world-space point
I was a vr developer fen tried a lot like that once.
so, use the transform of Player to transform input positions
You could probably rephrase this question:
Should I use a switch for determining whether a melee or range attack was used or add an additional layer of inheritance to not need this small selection
I had thought the switch held your guns initially. A selection of three is fine.
Although, hm, this feels incorrect.
If the player walks 3 meters to the right, their hands will also be about 3 meters to the right
aren't i already doing that with this line though?
Vector3 targetPosition = actions["Position"].ReadValue<Vector3>() + followTarget.position + followTarget.TransformDirection(offset);
except just relative to the camera rather than whole player
It would be incorrect to transform [3,0,0] with the player's Transform (which would give you [6,0,0]
I'm talking about transforming the value you get from actions["Position"].ReadValue<Vector3>()
oh as in transforming it to a relative direction instead?
No, transforming the point
transform.TransformPoint(...) will turn a local-space point for transform into a world-space point
ah right im with you
Does the XR Origin object ever move?
I'll have to double check as im not completely sure, but i believe it moves when you physically move in your play space IRL, offset from the centre
the entire XR Origin object moves when your headset moves around? that sounds wrong
yeah i didn't think it did, but i did a quick google that told me otherwise, let me test real quick, i've never seen it moving personally
The origin represents the center of your playspace, and input tells you where the controllers are relative to that origin
Does the player ever move around without actually moving in real life?
yeah it doesn't move, you're right
e.g. can you float upwards?
you can yes, but my code correctly works for moving like that, just not rotating as well
are Main Camera, Left Hand, and Right Hand being driven by your headset and controllers?
I'm trying to figure out which parts are actually moving here
Camera is moving and rotating using a built in unity script, and when i move/rotate my head in real life, that's the position that gets updated. Hands are using the Vector3 obtained from the input system, which is their relative position to the XR origin. I realise that in moving myself physically my camera can escape from my model, but i plan to fix that later, and i don't believe that's an issue here, but i may be wrong
I think that ~is~ your issue here
The camera doesn't care about whatever is happening to Player
It's just trying to position itself relative to the XR origin
(moving the XR origin should cause your viewpoint to move around in game)
So as you translate and rotate the player, nothing actually happens to the world-space positions of the camera or the hands
RIght, i see what you mean. Should my player model and rigidbody, etc be a child of my camera then instead of the other way around?
I've only ever dealt with moving the player non-physically, which I achieved by moving the entire origin
I'm not quite sure how I'd deal with rotation as well
I'd ask about that in #🥽┃virtual-reality . Someone with more experience might have better ideas.
You need to move the camera and hands into the right spot in the world after both translating and rotating the player.
I haven't got any clear ideas off the top of my head -- it always winds up getting too complicated to be correct
I mean, i could always not rely on the built in unity script and get the headset's relative position to the XR origin aswell if that would help. I'm generally hesitant to use that virtual-reality channel as in the past i've not gotten any answers there.
Does the player's movement cause the rigidbody to move and rotate?
If it does, then you have to avoid "double counting" that movement, as described here
it does yeah. The rigidbody is on my "Player" object
i suppose, i could have an empty object as a child of XR origin but a parent of everything else that could adjust itself based on my camera's position, and then i wouldn't have to worry about moving the camera itself, and everything else would move along with it, maybe that would work?
What is the purpose of == operator when .Equals exist? If i override Equals should i override == too because it is called equality operator?
Is there any reason to make them behave differently?
- For syntax sugar basically - it's prettier
- The == operator is a static method and therefore isn't going to throw a
NullReferenceExceptionif the left operand is null
If i override Equals should i override == too
Not necessarily, but often, yes.
That is the only difference right?
What are the case where equals and == should behave differently?
This is weird that c# allows different behaviour for == and equals
Well HashCode and Equals are the things that are used for collections like HashSet or Dictionary (by default at least, assuming you don't provide a custom comparator).
I think it's pretty common to define HashCode and Equals for a class so you can use it in collections and then not define a == operator at all because you don't foresee checking equality in your own code ever.
== can also be defined differently for different operand types
.Equals() always takes an object parameter and therefore there can only be one of them basically.
Well you could define a .Equals with a different param type but it wouldn't get used in collections.
Surely collections use the typed one you declare with IEquatable<T> IEqualityComparer<T>
overriding equals but not == looks like anti pattern to me because == is called equality operator
nah it's quite common
yeah if you use IEquatable they do use that IIRC
Is there example of system class in c# that override equals but not ==?
It may also be desirable to leave == as a "reference equality" check and have .Equals be a "value equality" check for example
of course you could always use object.ReferenceEquals
i have no idea off the top of my head
That doesnt make sense tho, == is equality operator which means it compares equality, not reference equality (unless the equality itself is reference equality)
That's the fun part - you get to decide what "equality" means
and that's why C# lets us provide custom implementations for these things.
In some cases, that may be giving you enough rope to hang yourself, but isn't that part of the fun?
Is there a good c# book/source/paper/documentation which provide guidance on == and equals?
The manual perhaps?
The manual only tells how it work, not how it should be used tho
Because there is no rule on how it should be used. It's the same as naming and other conventions. They change between communities, companies and individuals.
For me, == would usually be reference equality and .equals member wise equality if I'm gonna define these myself.
Which I wouldn't in 99.9% of cases.
That would be anti pattern because if you use library which treat == as equality and not reference equality your code will be more confusing to read
This is the part where you read the code and docs of the library to understand how it works.
But you can just define separate methods for MemberwiseEquals if you really don't like the idea. As I said, it's a preference/convention.
Hmm thanks everyone, in that case i need to make decision on whether i should treat == as equals or reference equals
Maybe just don't define these manually. Is there a good enough reason for you to do it?
The simpler you keep it, the better it is.
If you can't decide how to treat them, you probably don't need to redefine them anyway.
When I want to be really explicit about if my code is checking for reference equality I just straight up use ReferenceEquals(a, b) and call it a day.
Oh nvm i finally found the guidance about == and equals on microsoft learn
Can you share with us? I'm curious what they say.
It basically says treat == as equals for value type, and for reference type, in most case don't override the ==
sounds about right
When I see == I generally assume it's reference equality for reference types
If you want value equality on a reference type it's probably best to just make a separate method.
Anyone know a way to pass an arbitrary math formula to compute shaders?
Only way I could think of is interpreting a string but that requires a lot of steps, not impossible just really annoying
You mean like - letting the end-user write one at runtime?
Yeah
interesting idea.
I have no idea how you'd do that tbh.
Can’t really interpret it in cpu cause variables like x and y would be different in gpu each thread
The only way I can think of is code gen a compute shader around that formula and compile it at runtime.
Maybe you can pass in an array of structs that represent binary operations?
Not a bad idea
Thought of that, doesn’t seems unity lets you make compute shaders at runtime
Not by default for sure. You'll need to do extra work for that.
Like just make a new file and write to it?
Is there a way to compile it if you do that?
If you had access to the unity source code it would be possible to implement it. Wether it would be reasonable or not is a different question.🤔
unity? Open source? Ahaha
You can get it with enterprise license 🤷♂️
But yeah, I guess what Osmal suggested is the most reasonable way so far.
Didn’t realize that actually, still i would have no idea where to even start lol
Seems so
Can someone help me understand the warning:
Co-variant array conversion from CoffeeModifier[] to ButtonDisplayable[] can cause run-time exception on write operation
CoffeeModifier inherits ButtonDisplayable
Does the exception only arise if I write a ButtonDisplayable that is not a CoffeeModifier? Is it fine to leave the warning if I never have to change the array
In the example, going from an array of strings to objects would generate the warning.
I'm simple Graphics Raycasting and for the first frame, no objects are detected. In subsequent frames, objects are detected fine. Event system is assigned in Inspector and never disabled. Does anyone know why that could be? Here's my code:
Debug.Log($"Casting at {touchInfo[touchIndex].position}...");
pointerEventData = new PointerEventData(eventSystem);
pointerEventData.position = touchInfo[touchIndex].position;
List<RaycastResult> rayResults = new List<RaycastResult>();
graphicsRaycaster.Raycast(pointerEventData, rayResults);
Debug.Log($"Casting hit {rayResults.Count} objects");
I've attached a shot of the Scene. Thanks
First frame of the entire application? Or what do you describe as "first frame"?
When I hit Play in the Editor
So you hit play and click somewhere and your casting at debug log is not firing or your rayResults.count is 0?
Just checked your console, got it. Your hits are 0 on first click.
Yes. I have also taken out the casting to just update and still doesn't hit anything on the first frame. Rather strange
private void Update()
{
Debug.Log($"Casting at {touchInfo[0].position}...");
pointerEventData = new PointerEventData(eventSystem);
pointerEventData.position = new Vector3(480, 540, 0);
List<RaycastResult> rayResults = new List<RaycastResult>();
graphicsRaycaster.Raycast(pointerEventData, rayResults);
Debug.Log($"Casting hit {rayResults.Count} objects at position {pointerEventData.position}");
return;
ProcessTouchType();
ManageLiveParticles();
}
Edit: Feeding a direct value into the .position property has the same issue
Maybe you have to "wake up" the eventsystem with a "start raycast" to avoid that issue.
Could it be a matter of execution order?
Ah wait, I misinterpreted your situation. You are not waiting for user input, you just raycast a custom ray right at the start of update running no matter the user input, right?
What are you trying to hit? Is it actually a UI object?
Yes. In this part of my script, I fake user input for testing purposes 🙂
Yes, it's the highlighted object in this shot.
I have since created a new scene with the same code as above and the issue is still present, so its nothing in my scene. I have added a delay of 10 frames before I do anything with the script to get around the issue
One possible cause is that the raycast is performed while the object is not placed where you expect or doesn't have a graphic that can be hit yet.
It seems like the image is empty on start
Assuming you assign the image in update(of a different script) as well, there's no guarantee that this happens before the raycast
It doesn't need a Sprite to raycast
Wdym? If there's no image, then nothing would be hit
Image is Raycastable regardless of if a Sprite is assigned 🙂
Ah, okay. But the image has 0 size.
It's stretched to the canvas size. I tried that even with standard fixed placement covering full screen and its still not a fan. I think the Graphics Raycast stuff must wait for something from the canvas to be ready
Not sure what it is however
Perhaps the raycast happens before the canvas rebuilds at the start or something
Try using late update
Or wait 1 frame
Hi friends, I have one scene with room design and one orthographic camera I want to zoom the camera when I double-click on the particular wall if I click on the wall with a green circle the desired outcome will be like in the next image only selected will appear on camera. So, how do you position the camera via script? Please help! I have tried this function where I pass the "targetObject" as the selected wall create a new orthographic camera and try to put it in front of the wall and look at that wall but it's not working in every direction wall. Please help!
{
if (targetObject == null)
{
Debug.LogError("Target object is not assigned.");
return;
}
// Create a new GameObject for the camera
GameObject cameraGameObject = new GameObject("OrthographicCamera");
// Add a Camera component
Camera camera = cameraGameObject.AddComponent<Camera>();
// Set the camera to orthographic mode
camera.orthographic = true;
// Set the orthographic size
camera.orthographicSize = 5;
// Position the camera with the given offset
camera.transform.position = targetObject.GetComponent<Collider>().bounds.center + offset;
// Make the camera look at the target object
camera.transform.LookAt(targetObject.GetComponent<Collider>().bounds.center);
// Adjust the rotation so the camera is aligned correctly
camera.transform.rotation = Quaternion.Euler(0, targetObject.transform.eulerAngles.y, 0);
Debug.Log("Orthographic camera created and positioned.");
}```
First question is what is "offset"? In theory this should work if the camera is say -10 z from the object center and then is made to "look at" the object center.
You also override the rotation after using LookAt soo...
@steady bobcat "offset" is the distance between the wall and the camera I put it at -5, the problem is that the camera does not position correctly for each side of the wall
If you position the camera as you want, what global pos does it actually have?
if you just move it -5 on a single axis then the result you got above makes sense (as i presume your room is "axis aligned"), you need to think more carefully what you need to do to maintain the same camera pos + angle.
@steady bobcat each side wall faces the same side there are no rotations to the walls. That's why I can't know on which axis i should put the offset.
OH do you actually want it showing it "square"
you can use the normal of the face to move the camera out in the correct direction easy
then look at
@steady bobcat how can i get normal of the face? is it from mesh?
If you raycasted i think you can grab the hit normal and use that which should be correct depending on the collider used
if using input system im not 100% sure if you can get the same data
oh i used raycast thanks I'll try and let you know.
(I'm making a 2D top down shooter for context)
Anybody know how to interrupt animation states? I'm having some major issues using the animation system trying to fix a bug in my game where the player has multiple weapons and one of them is a boomerang which is animated compared to most of the others.
The problem is that the boomerang has a slight delay from when you start throwing the boomerang to when i actually becomes a projectile. In that little window, if you switch to another weapon, then back to the boomerang, instead of going back to the "boomerang idle" animation, it just plays the "boomerang throw" animation. It's even worse when the player switches to another animated weapon like the RPG after switching to a non-animated weapon after trying to throw the boomerang but switching to a non-animated weapon then the RPG causing the player to throw the boomerang before actually showing the player is holding the RPG.
Sorry if this is hard to read, i'm just really annoyed over this whole problem. The Unity animation system is my least favorite part of Unity.
@steady bobcat i get these four different normals for four walls how can i use this to place camera and rotation?
Must be due to how you have your states and transitions set up. And/or the different weapons and code to switch between them as well.
https://drive.google.com/file/d/1AYF3Gx_v0a4YraHDENBaAbJZvxZf1YXK/view?usp=sharing if anyone cares enough and also has the time, i have the project here:
Maybe start with sharing screenshots/videos demonstrating the setup and the issue as well as sharing your code.
i gotta go to class now, hopefully i'll remember when i get back
You can use the collider center and add the normal to it to place the camera 1 unit away.
Then a look at should be enough
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hi, i was making a isometric shooter so i want my character to rotate towards my mouse but im getting wierd offset
private void RotateGraphicsTowardsMouse()
{
Vector3 mousePosition = Input.mousePosition;
Ray ray = mainCamera.ScreenPointToRay(mousePosition);
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
if (groundPlane.Raycast(ray, out float distance))
{
Vector3 worldPosition = ray.GetPoint(distance);
Vector3 direction = worldPosition - graphics.position;
direction.y = 0;
if (direction.sqrMagnitude > 0.01f)
{
Quaternion targetRotation = Quaternion.LookRotation(direction);
graphics.rotation = Quaternion.Slerp(graphics.rotation, targetRotation, Time.deltaTime * 10);
}
}
}
if the laser is on the floor plane im guessing it lines up after all
That's exactly what your code does.
you can move the plane up by the aim height to make the laser match
but i think the rotation will be the same either way 🤔 (maybe? im not sure)
Making the gun aimable on the y axis might help
yeah if i put laser on ground it works good
i tried putting a little offset but on each quater the offset is different so cant put offset too
The difference in the video looks like it's because caused because of the angel of the camera + model. The cursor is aligned with the middle of the body, so it will be below the laser at all angles that aren't 0/ 180
It's just an opitcal illusion, imo
yup, but it will look wierd when player try to aim
have you looked at other games and evaluated how they do it?
this will not be a viable solution
Hi ! I have been wondering if there is a way to call a function that would play from the Entry node of the base layer in the animator ?
like : animator.Play(form the entry state of that layer);
i was trying to copy the ascent's controller but not sure how they do it there aim line up on the laser
Hi , does anyone perhaps have some knowledge they can share regarding this error ? I just have a very basic script to display my webcam feed onto a RawImage but for some reason, even though it's worked fine some time ago, it just pops up with this error and refuses to display the webcam in question.
I've tried setting the resolution and fps in script which didn't seem to do anything and also tested with multiple cameras. Any suggestions would be greatly appreciated
Can you get a list of supported resolutions fort a webcam, maybe?
I've tried as well, but even if it is on a supported res it just comes back with the same thing
okay, so the device doesn't have an empty list of resolutions
this is the one i am trying to copy @trim schooner
If you mean by using device.availableResolutions, it returns null because it's on Windows
how do you know what resolutions are supported, then?
ok, i've recorded the issues. The second clip shows where the actual bug happens. When i try to throw the boomerang, i switch weapon then back to the boomerang to show it just automatically throws it.
and so you can look at the code, here's the boomerang state machine script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoomerangStateMachine : StateMachineBehaviour
{
// OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
if (Shooting.selectedWeapon == 5)
{
animator.ResetTrigger("Selected weapon is rpg");
animator.SetTrigger("Selected weapon is boomerang");
}
if (Shooting.selectedWeapon != 5)
{
animator.ResetTrigger("Throw boomerang");
}
}
// OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
if (Shooting.selectedWeapon == 5 && Input.GetButton("Fire1") && Shooting.canShoot && Boomerang.boomerangCount > 0)
{
//animator.SetTrigger("Throw boomerang");
}
}
// OnStateExit is called when a transition ends and the state machine finishes evaluating this state
override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
animator.SetTrigger("No boomerangs left");
if (Boomerang.boomerangCount == 0)
{
animator.ResetTrigger("Throw boomerang");
animator.ResetTrigger("Boomerang reaquired");
}
}
}
The RPG one is too long to include in this message as well though, i'll send that one after this message.
I just assume, for example an HD camera would be 1920x1080 and rations below that? There isn't really much else to go off of to my understanding
And here's the RPG one. (yes, there's a lot of disabled code, i know.)
using System.Collections;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using UnityEngine;
public class RPG : StateMachineBehaviour
{
// OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
}
// OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
if (Shooting.selectedWeapon == 4)
{
animator.SetTrigger("Selected weapon is rpg");
animator.ResetTrigger("Selected weapon is boomerang");
}
if (Shooting.rpgIsReloading)
{
//animator.SetTrigger("Rpg reloaded");
//animator.ResetTrigger("Fire rpg");
//animator.SetBool("rpg empty", true);
}
else
{
// animator.SetBool("rpg empty", false);
animator.SetTrigger("Rpg reloaded");
}
}
// OnStateExit is called when a transition ends and the state machine finishes evaluating this state
override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
//animator.ResetTrigger("Fire rpg");
//animator.ResetTrigger("Rpg reloaded");
//animator.SetBool("rpg empty", false);
}
}
the third script which is a monobehaviour one that's actually attached to the player is straight up too long to send in one message here so uhh..
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
It's just strange to me because I don't know if the issue actually has to do with the resolution of the camera, because previously when I tried this it just worked with any camera
use a paste site, for all your code
my badddd, i'm new here ._."
also why is there no debugging in your code?
cuz i'm dumb probably
how do i use xr interaction manager to snap an object to the players hand when grabbed? it's using a ray and grabbing it with the same offset as when it was picked up. im trying to use direct interactor but it doesn't seem to do anything. im using the default xr origin rig prefab on unity 6.0.27f1 xr interaction toolkit 3.0.7
You're not dumb. As Steve mentioned, you should really get dbeugging in your project. Doesn't have to be much, just simple logging
Helps a lot. Often completely useless, until it's not
It's a pretty bad idea to handle your logic in StateMachineBehaviour.
Because it hard-depends on the actual state of the animator. You want your logic to run independently of the animator. The animator should only handle animations.
if you have a singleton as an additive scene, you can't use single-load scenes at all without destroying the singleton then, can't you
unless you ddol it
look, the animation system always frustrates to a point i just end up writing yandev levels of idiot code.
I think that's fine. You're punting the logic from your components to the state machine.
You just have to be conscious of that dependency.
Although, thinking about it for more than 5 seconds, I'd rather not put too much of my game logic in there.
I'd mostly just want to use them like animation events (but for entering and exiting states)
i also have the Shooting script that triggers the animations
Yeah. That makes things even more complicated. I'd recommend scratching the StateMachineBehaviours and rewrite the logic in a MonoBhehaviour. Make sure you handle all the animation parameters in one place so that there are no scripts fighting each other.
When you have that handled, and if the issue still persists, it's probably due to the animator states/transitions setup.
....you have a point.
someone ping me if they know pls thx
One big headache is that StateMachineBehaviours cannot store references to scene objects, since the animator controller is an asset
i just chucked pretty much all of the state machine stuff into the Shooting scripts Update method and it works fine though it didn't fix the issue at all (probably horribly inefficient as well ._.")
Start from looking at your state transitions in the animator at runtime. As well as animator parameters.
Sharing the new code would be helpful too.
the update method is too long for one discord message ._."
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
use a paste site for that much code
like github?
Use Scriptbin to share your code with others quickly and easily.
no, like one of the sites linked in the bot message
I guess you could use a Gist, though
i'm blind
hello everyone, how do I make it so that when an object touches something, music starts playing only when it collides, let's say I have music for 6 seconds
when collide, start playing audio clip
that's 2 separate parts
try researching for those separate parts
Use Scriptbin to share your code with others quickly and easily.
"unity how to detect collision", "unity how to trigger audio"
Looking at the videos you shared, your animator setup is a mess. First of all, most of the parameters are logically bools, not triggers. You should not have that many triggers active at the same time. A trigger is like an event. It's meant to be consumed almost immediately. If your parameter defines a long lasting state it should be a bool.
The only params that logically make sense to be triggers are: Swipe, Throw boomerang and Fire RPG.
Swipe is for a scrapped weapon ._."
You should write down the logic that you want to be followed on paper. Ideally, make block schemes. When you have it planned on paper, implement the animator states and then write the code that sets the required parameters.
i fixed it. Good LORD that was hell. Thanks a ton for telling me to make most of the params into bools. Really saved me.
Thanks man, it helped a lot!
how do I override/take an action on this menu item? I thought this would do it, but no: ```[CreateAssetMenu(fileName = "SOTest", menuName = "GameVersionData/SOTest")]
public class SOTest : ScriptableObject
{
public int anInt;
[ContextMenu("Reset")]
public void Reset()
{ anInt = 69; Debug.Log("Reset called"); }
}```
Do I need to use a different method signature for the Reset button to be enabled?
Name collision!
"Reset" is already a context menu item.
which...well, it's supposed to run the Reset method, actually
That may be screwing up the menu
That what I thought.. I thought unity used reflection to find a paramtererless void method named Reset
Do you want Reset to run upon creation of the asset, or should it only run when you pick a specific menu item?
both
Okay, just get rid of the ContextMenu attribute
but I can make two fuinction names if needed
see if that makes it happy
Maybe restart the editor?
I know that I've had problems with [CreateAssetMenu] items not updating until after a restart
ok, gimme a sec
nope :(.. hmm am I trying to Reset() wrong? does that button not do what I thought it does?
the other option is "EditScript" which feels.. different than what I need
Is "SOTest" an asset in your project window?
the Reset item is not grayed out for me
and it works as expected
(unity 6000.0.24f1)
oh.. using that same scimple script!!? ok, thats a good sanity check thank you Fen
yeah
the Reset function is called upon asset creation, as well as when I click Reset
even with the ContextMenu attribute being there
hmm.. ok prolly me and the old ass unity version I'm running, will copy project and try in later version. Thanks again- big help!
It looks like it completely ignores your ContextMenu attribute if its name is Reset. It does the normal reset operation (setting all serialized fields to their default values) even if "Reset" is supposed to just call that Reset method
I dunno what would be causing it to gray out the Reset button
negative
will double check that.. currently upgrading unity version of project
That would be plausible (but that'd have caused a Safe Mode prompt when reloading the editor)
pretty sure Context Menu methods need to be static
speak of the devil:
litteryaly the SECOND you said that
no, that's for MenuItem
ContextMenu is for interacting with a specific item in the inspector
hm, this should've come up while restarting the editor the first time
You don't even need context menu for Reset, it's built-in
ah.. it was OTHER stuff in the project (not that TestSO) fixed.. testing now
Yeah, and we tried removing the attribute already
If you just changed major version numbers, obsolete/deprecated code could have gone away entirely and broken the project
I know that a few enums got renamed between 2022 and 6
had to go in and rewrite those myself
that was it.. the unity8 version- working as expected in 2022
unity 8 😱
(yes, I tend to lag.. I'm old)
Try testing on a fresh SO script and let IDE autocomplete Reset method
oddly, still not showing up in autocomplete.. but whatever, I can deal with that- prolly need to create a new project in new version of unity, and move all my scripts in.. never like working with upgraded projects.. always issues like that
any particular version you recommend? or just latest?
When using rider debugger anybody have issue on it not showing variables because they are "out of context"
Buddy's living in the future
That implies that those variables don't currently exist
e.g. they're locals in a method that you aren't currently inside of
Should they be visible inside method that is currently inside local scope. Like show the ones right above the current local scope
But still inside method
by "local scope", are you referring to a block statement?
if so, then yes, everything in your enclosing block will still be in-scope, so it'd be weird if the debugger said they were out of context
{
float foo;
{
float bar; // bar and foo are visible here
}
}
I will show example quickly once i boot up computer
I did it now and it worked like expected. Huh, maybe it will repro later
heh.. ye olde tyme: "turn it off and back on"
Its weird cause i have had happen fairly often, but not right now
I have a MyType<T>, and I have a CustomPropertyDrawer(typeof(MyType<>))
How can I access either a static property from MyType inside my Drawer?
I have to provide some T to even type it out in a way that the IDE doesn't scream at me
but I don't know what's a good "default" T to provide
You can only access things that are guaranteed to be members of T
If T is an unconstrained type parameter, you can access nothing
Oh, wait, I see
MyType<T>, not T
Hmm, I'm not sure what the "nicest" way to do that would be.
optionally - a way to do null.ToString() would be fine lmao
what are some of them?
you can just pick an arbitrary type, of course
this variable can be const, it can be readonly, anything, I just want a consistent way to get the string in my Drawer
I feel like it doesn't belong in that type at all
I'd rather not... but I will if I have no better ideas
it's only used there, ever
ah!
public class Test<T>
{
public const string NullString = "Null";
}
public void Foo<T>(Test<T> item)
{
var x = Test<T>.NullString;
}
That does work.
What's the actual problem you are trying to solve here? What's the use case of NullString = "null"?
It does feel a bit odd.
not typing == "null" 10 times across 2 scripts
I forget how the static member even behaves there -- does every parameterization of Test get its own static member?
If you just want to turn something that is potentially null, into its string representation, $"{foo}" works.
no - I specifically am looking for the null.ToString() equivalent
I do want to point out that statics on generic types are separate from each other when the generic type parameter is different. Foo<int> could have different values in its static variables than Foo<long>
I'm confused why you insist on maybeNull.ToString() when you could do $"{maybeNull}".
ah, so it does
ok, how about ANY string, then
that'd solve my problem well enough
what are you actually trying to accomplish with this
I'm very confused, yes
This sounds like a XY problem.
Show your existing code.
this is the Y in the XY problem
https://xyproblem.info/
what is the X
Presumably you can just make this a const inside of InspectableTypeDrawer
without further context I can't see why it needs to live in another type
how do I access it from InspectableType then?
I need it in both places
for the what am I doing? this, just modifying the script from the first answer
tbh I would just put it in another static class
at that point, it's a constant string that multiple types care about
it has no meaningful association with those types
well, InspectableTypeDrawer, plus an infinite family of InspectableType types
nope, the family itself doesn't need that
Importantly, the string has nothing to do with the exact type parameter of InspectableType<T>
since it's just for the inspector
I thought you said you needed it within InspectableType as well
within InspectableType<T> but not anything that derives from it
although that's not a problem since they, well, derive from it
so they'd have easy access if they wanted
but they don't
Making it a static member of InspectableType<T> means that every single parameterization of InspectableType<T> has its own static member
I don't care what the classes deriving from InspectableType<T> have, they don't need it
only the class itself and its drawer
is there a way to do it or do I just live with nothing
I am strictly talking about all of the different ways to parameterize InspectableType<T>. There is no "deriving" here.
InspectableType<int> is a different type from InspectableType<float>. InspectableType is an unbound generic type -- hence why you can't do anything with it beyond passing it to typeof.
I'd really just make it a const in both types and call it a day. Minor duplication isn't an issue.
(and consts go away during compilation)
much more reasonable than static members, actually, since those will not go away
I'll just do this then... slap a comment and that's it
switched it to const though you have a good point
I am working on a package that's almost entirely code. Is there a particular version of Unity I should use to develop it?
I'm worried about the serialized data confusing an older version of unity
e.g. I install the package on disk into a Unity 6 project
this means that Unity is going to start writing .meta files into the package folder
which are generated by a very new version of unity
nominally, even someone on Unity 6000.0.23f1 would be "downgrading" when installing my package
since I'm on 6000.0.24f1
assuming you don't set any of the default references or change anything else in the import settings for the file the meta file should just contain the fileformatversion and guid so it really shouldn't be a problem
yeah
and I imagine that the MonoScript serialization format doesn't change constantly
(interestingly, force-serializing it causes some extra stuff to be written...)
version 2!!
why on earth is information about asset bundles in there
hello everyone, how do I make it so that when an object touches something, music starts playing only when it collides, let's say I have music for 6 seconds
Use OnTriggerEnter or OnCollisionEnter
public AudioSource music
OnTriggerEnter
music.Play();
void HandleSpannerTwist()
{
// Get the distance between the spanner and the camera
float dist = Vector3.Distance(insertedSpanner.transform.position, Cam.transform.position);
// Get the mouse position in screen space, then convert to world space
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
Vector3 mouseWorld = Camera.main.ScreenToWorldPoint(mousePos);
// Get the vector pointing from the spanner to the camera (the "upwards" vector for rotation)
Vector3 upwards = insertedSpanner.transform.position - Camera.main.transform.position;
// Calculate the desired rotation of the spanner to face the mouse position
Quaternion targetRotation = Quaternion.LookRotation(mouseWorld - insertedSpanner.transform.position, upwards);
// Smoothly rotate the spanner towards the target rotation
insertedSpanner.transform.rotation = Quaternion.Slerp(insertedSpanner.transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
// Additional actions or logic, such as charging the generator, goes here
ChargeGenerator();
}
I am trying to make a handcrank (in code spanner) that the player rotates using his first person crosshair to recharge a generator, this is my code so far, my problem is that i want the crank to only rotate in the X-Axis while Y and Z are still 0 how can i do this?
Quaternions are not my strength
ooh we're doing rotations
I suck at rotations
is that a function?
you will create a plane that pases through the center of the crank and whose surface normal points along the axis of rotation
let me make a shitty mockup
Planes are super not rare!
that would be really helpful! thank you
I will defend Planes to the death
You're going to raycast from the camera onto this plane
Conveniently, Plane has a method for that!
do i need to change my model/hitboxes for the crank?
No.
This will have nothing to do with physics at all
You'll use the Raycast method to find where on the plane the player's mouse is positioned
Given a point on the plane, you can find a direction from the center of the crank to the point
That's the direction the crank should rotate towards
Finally, you'll use Quaternion.LookRotation to compute a rotation
Plane plane = new Plane(crankAxis.up, crankAxis.position);
Ray ray = Camera.ScreenPointToRay(mousePos);
if (!plane.Raycast(ray, out float distance))
return; // your mouse didn't hit the plane at all
Vector3 hit = ray.GetPoint(distance);
Vector3 direction = hit - crankAxis.position;
Quaternion rotation = Quaternion.LookRotation(direction, crankAxis.up);
The resulting rotation would make an object's blue handle (the +Z direction) point towards the hit point
Its green handle (the +Y direction) would be aligned with the crank axis
You may need to adjust this a bit if that doesn't match what you have
This doesn't handle clicking on the crank, mind you
You might use physics for that
This'll just let you wave the mouse all over the place while turning it
i already have some code for that which i think should work fine
they're super useful
Ideally, you should have an object whose pivot point is in the crank axle, at its base
this would be the crankAxis i used in my code
its green arrow should point along the axle
i modeled the crank with that in mind the pivot is at the base
This would be an appropriate setup
The blue arrow points in the direction of the handle
its not exactly at the base
As long as it's vaguely near the base it'll be fine
alright
If you want to visualize how this'll work, create a plane and parent it to that object
you can then imagine shooting rays at that plane from the camera
i will do that
again, thank you for explaining this to me with visualised examples and everything
no prob! (:
rotations can be really frustrating; you'll often figure out something that mostly works, but then blows up in a few cases
i imagine they're a lot more useful in 2d right? i mostly do 3d stuff and i've never once heard of them
i think i do see how they can be useful thouhg
i forgot that the crank can be taken off and placed to other places and when i do that the green axis no longer points away from the base meaning the plane is made in the wrong axis, how can i fix this?
are you in "Global" mode in the scene view?
yes
set it to "Local" if so -- check the top left corner
that will show you the local directions of the object
red is right, green is up, blue is forward
i changed up to right here
Plane plane = new Plane(insertedSpanner.transform.right, insertedSpanner.transform.position);
Yep, that'll be the correct move
You'll also use transform.right as the second argument to LookRotation
was just about to ask that
alright
something weird is happening now
the crank rotates in all axis
Can you show me your code?
void HandleSpannerTwist()
{
float dist = Vector3.Distance(insertedSpanner.transform.position, Cam.transform.position);
Plane plane = new Plane(insertedSpanner.transform.right, insertedSpanner.transform.position);
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
Vector3 mouseWorld = Camera.main.ScreenToWorldPoint(mousePos);
Ray ray = Camcamera.ScreenPointToRay(mousePos);
if (!plane.Raycast(ray, out float distance))
{
return;
}
Vector3 hit = ray.GetPoint(distance);
Vector3 direction = hit - insertedSpanner.transform.position;
Vector3 upwards = insertedSpanner.transform.position - Camera.main.transform.position;
Quaternion targetRotation = Quaternion.LookRotation(direction, insertedSpanner.transform.right);
insertedSpanner.transform.rotation = Quaternion.Slerp(insertedSpanner.transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
ChargeGenerator();
}
Oh right, I just realized -- LookRotation will still behave wrongly here
It gives you a rotation that aligns your blue arrow with the first direction, using the second direction to decide how to roll around that axis
One other issue is that Slerp is going to take the shortest possible path
I think that'll make it rotate properly as long as the starting and ending rotations are around a common axis, though
(oops, i didn't finish that thought)
would using slerp cause the crank to get stuck at certain points
It's generally used to figure out how to orient your camera
you look in one direction, using a second direction to decide what should be "up"
but we're not using forward and up; we're using forward and right
Can you modify the crank so that the green arrow is pointing along the axis? That would make things easier
do you mean change the model?
Either that, or by parenting the model to an empty object and then rotating the model
- Root
- Crank Model
Yeah, you'd want the component to be on the "Root" object
Before you do that, though, there's one other option...
How to Disable Script Updating Consent Popup
actually, lemme test something
okay, yeah, it works perfectly when the up direction aligns with the axis
Yes, perfect
It goes nuts if I use the same code with the red arrow pointing outwards (with transform.right swapped in)
I think the issue is that LookRotation wants to make your green arrow (the up direction) agree with the second direction you give it
But we want the red arrow to agree with that second direction (so that we spin around the axis)
So it's off by 90 degrees and freaks out
i think it works right now
One other thing -- you might want Quaternion.RotateTowards instead of Quaternion.Slerp here
the former will let you move towards the target angle at a constant rate
the latter will be faster when you're further from the target
which is okay, but it'll also be a bit wonky -- see https://unity.huh.how/lerp/wrong-lerp
Yeah -- you can measure the angle between the old rotation and the new rotation
This will always be positive
well if the player is going to keep spinning it wouldnt it be...
If you want to be able to measure going both forwards and backwards, then you might want Vector3.SignedAngle
Vector3 one = rot1 * Vector3.right;
Vector2 two = rot2 * Vector3.right;
float delta = Vector3.SignedAngle(one, two, Vector3.up);
You need that third vector as a point of reference
to decide if the angle is positive or negative
i think i am going to sleep now
thank you for your help
i was trying to fix this for like 3 hours
have a nice day
you're welcome (:
Hello, I recently updated to unity 6, and I can't seem to get the light2D to be found in scripts. I changed the reference to no longer have the experiential path but it still can't seem to find it. I also tried regenerating the project as well. What else can I do?
Nevermind, I just had an idea that is should just add any assembly with the name 2D in it and found the assembly Unity.RenderPipelines.Universal.2D.Runtime to work.
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://paste.mod.gg/imkdeljkvcym/0 Anyone have any ideas why it would still be playing the recoilAnimation. all the other ones stop if the currentMagazineAmmo is 0
A tool for sharing your source code with the world!
You call _recoilAnimation.Play(); whenever this function runs and currentMagazineAmmo is above 0, but nothing ever tells it to stop playing at any point from what I see. What is _recoilAnimation?
a reference to a script that handles a procedural animation.
thank youuu!!
got it
called the _recoilAnimation.Stop();
is anyone able to help with this? i never did get it resolved from yesterday and im still completely stuck after spending logner on it today
this is an interesting mechanic. are you saying you want to "hold" an object and make it appear stationary in screen space, but naturalistically moving in world space?
No, for context, i'm working with VR and have 2 controllers, the input im receiving from them is their relative position as a Vector3 to me, the script is controlling the position and rotation of them ingame, and they should sync up in real life, if that makes sense
okay. so all you want is that the objects behave the same as the controllers in world space?
yeah
they track perfectly for movement, just not rotation
and the objects must be NON kinematic rigidbodies while under the influence of the controller?
yeah
you actually mean that the objects should be "tracking in relative space to the controller while the button is pressed" right? like you press a button, and now they're "tracking", but they don't fly into an absolute world position and orientation
not on a button press, they need to track all the time
okay
i want you to think deeply about that
they're probably not doing that
like even at the beginning of the game, yes? they're not in absolute world space
they're not no, but they'll travel to where i need them to be, the issue is with their positioning when i rotate, they dont rotate with me
are you familiar with physics joints?
you "simply" attach (a) joint(s) to the controllers in your scene
your choices in how to do that reflect what kind of behavior you want
Do you mind linking to the message again, it doesn't show for me
Sounds to me like you just need to rotate the relative target position by the character's rotation
you are currently reinventing joints
And apply torque to match the rotation
so you can use joints, or you can try to author joints from scratch
i have a vague idea of how they work, but i've never used them
you can start by adding a fixed joint to the hand, then connect it to the object in whichever way makes most sense to you
Sure, mind just letting me finish this game i'm in? I can get back to you then
Quaternion deltaRotation = targetRotation * Quaternion.Inverse(rb.rotation);```
This part might be inverted. Order of operations matters with quaternions
tracked pose drivers Just Work. it really depends on your gameplay
you don't want to reinvent either tracked pose drivers or joints
or use a vr interaction package from the asset store
since you have to do all the joint stuff at runtime
imo, because you don't get physical feedback, you will probably want to use a bunch of springs
you can study the asset store assets that do this to see how they make good interactions @mighty juniper
don't they not work with physics though? I thought that would just be the same as setting transform, and would cause my hands to phase through walls, i want to avoid that
i think you should use an asst and a grab interactable
I was using it initially, but its just a pain to use for my use case so i wanted to build it myself
end users have certain expectations regardless of what you want that have been defined by other games
hmm, but correct me: it looks like you just want these objects to behave as though they are grabbed by a hand
perhaps without visualizing the hand, but grabbed nonetheless
the cubes are just visualisations of what will eventually be a hand model
nothing is being grabbed at this stage
they are my hands
I dont think this is the problem though, my hand rotation works, just not when i physically rotate
you want a hand model that is permanently physically interacting?
and just behaves "well" around walls and such?
so grab a hand model
right now you are trying to reinvent grabbing.
Vector3 targetPosition = actions["Position"].ReadValue<Vector3>() + followTarget.position + followTarget.TransformDirection(offset);```
I don't see you rotating thet target position here. (What is offset?)
your approach is not going to work in any case. it's going to accumulate a lot of fixes as soon as you discover teh bugs
i want it to physically interact with its environment, i will still have grabbing. Kinda like how it works in HLA
i am 1,000% confident the vr interaction toolkit asset from the asset store can do this no? this sounds super conventional
I couldn't find any up to date tutorials for it, and i couldn't figure it out from the documentation, it seems like they change names of stuff very frequently, but maybe you can
I feel like you should do something likecs var localPos = actions["Position"].ReadValue<Vector3>(); var rotatedLocalPos = followTarget.rotation * localPos; var pivotPos = follorTarget.position + followTarget.TransformDirection(offset); // ? var targetPosition = pivotPos + rotatedLocalPos;
The second line being the key change here
okay game this out though. the asset definitely does what you need to do right?
i mean it seems pretty cut and dried
you just want hands and grabbing
you can definitely have this!
Offset is just a direction vector for offsetting from the camera, so they are further away
it exists
you don't have to worry about trying to do this yourself
the whole approach is wrong
Ok that's what I expected. Try out my suggestion
you aren't reading the right input actions, and you're not familiar with the VR input system idiosyncracies, and you aren't figuring out the angular velocity correctly either
😦
unity even has a built in package: https://docs.unity3d.com/Packages/com.unity.xr.interaction.toolkit@3.1/manual/samples-hands-interaction-demo.html
Will do when i get a chance, thanks
these don't have physics interactions though iirc, i tried out this demo scene
(Btw my example expects that followTarget is your character/whatever object's rotations you want to follow)
Not sure if thats the case
Id rather avoid paying £30 for an asset
yes that's right, ill give it a go now
that seems to do the trick! Thank you so much
although i could've sworn i tried applying the rotation like that before, but maybe it was my order of operations that was wrong
🥺
I just would rather stay away from the default framework to be honest as it feels really unreliable at times. And I'd rather have a deeper understanding of exactly what my code is doing, because i wrote it, rather than trying to twist their framework to my needs
I'm kind of going insane here.. I have a font that I generated two SDFs for textmeshpro. The fonts are identical, but one has an underlay and outline on the material.
The spacing is different between these two fonts and I can't figure out why. They look the same but the glpyh adjustment table is different for a variety of characters.. how would that happen?
same font face, same character spacing, just a different material (underlay and outline values)
individual glyphs have different adjustment widths but I don't know where these would have been generated from
Hello, i am working on a random structure generator, and am mostly done with the base of it, however I am occasionally getting this error (image 2)
private void roll()
{
blackList.AddRange(newRoomDirs); // adds already used directions to blacklist (1-4)
List<int> valid = new List<int> { 1, 2, 3, 4 }; // valid directions
valid.RemoveAll(v => blackList.Contains(v)); //removes all directions from valid contained in blacklist
int newDir = UnityEngine.Random.Range(0, valid.Count); //random index
blackList.Add(valid[newDir]); //adds newDir to blacklist, where error is
StartCoroutine(createRoomSpawner(valid[newDir])); //creates room in chosen direction
}
i can provide any more context if needed
Do some debugging.
Without context, I'm guessing the issue is that you have no valid directions left.
oh that might be true, let me check
or if there's 0 items left in the list, newDir = 0 (which doesn't seem to be a valid direction according to your comment), but valid[0] will be index out of range because there are no items in the list (where your code would try to read the "0th" - first - item)
or rather, what burrito said - if your blacklist has all the items in the list
yeah i forgot to check if count was 0, that fixed it! thanks
I'm working on a 2d pixel game, and would like the players to be able to change the color of some objects. Unfortunately, Unity's coloring via code looks really faded/washed out. Does anyone know of any assets or anything I can use to improve this? I'd like "Red" to actually look red, rather than a faded pink.
Sounds like it's just being affected by lighting? Try an Unlit material/shader if you want to ignore all lighting, or adjust the Smoothness/Roughness and other parameters in the lit shader
You might also have some post processing effects going on
Okay I completely forgot that your game is 2D. Are you using some kind of lighting? Maybe show a screenshot of the issue?
And the settings of the sprite renderer and its material
I suspect that the "washed out" effect is because by default, the sprite color is multiplied by the base color. So if you have a green sprite and add a red tint to it, it won't be red
Someone else is doing the programming on my current project. I just know from past experience (years ago), that this was an issue (and my current programmer brought it up recently)
we haven't actually implemented any coloring yet. I was just wondering if there was a better solution
I'd probably use a shader that has a mask texture for which parts of the sprite should be affected by color.
Or if you want to color the whole object, just use a white/grayscale texture. Then the coloring should work as expected
https://hastebin.skyra.pw/eyitejonev.csharp I'm struggling with this code, it's almost perfect but it still has problems. The player enters a collider and presses E for an action to occur (the camera changes and text appears) but the player's control is not deactivating in the right way. If I jump or walk while pressing E, the player freezes in the movement, continues walking or stays in the air if I jump, I need him to finish the last action before entering the animation. And another thing, when the camera returns to the player, some commands are disabled, like if I want to run, I need to stop pressing sprint and press it again.
Sounds like you'd want some sort of state machine or queue for the actions
Instead of DisableControls implement something like QueueDisableControls that only flags the controller to stop controls. The controller the can handle it however it likes. For examples, finish the current action before disabling.
when the camera returns to the player, some commands are disabled, like if I want to run, I need to stop pressing sprint and press it again
you explicitly set those to false in both DisablePlayerControls and ResetPlayerInputs
Does anyone know what would be causing an error like this? Double clicking on it doesn't bring me to where the error is being thrown, and I haven't touched anything in UnityEditor.Graphs. It started happening after I tried making one script inherit from a different one. There aren't any compile errors.
it's just an editor error, likely caused by the Animator or some other graph editor being open. you can ignore it
it's also unrelated to your own code
Ok, sounds good. I'm just confused because it wasn't happening before, but I'll ignore it. Thank you.
close any graph editor windows and it will stop so you can confirm that it isn't your code doing it (though i can assure you that it isn't your code)
I swear I had a problem like this and it was that the material had some property with slight transparency that when disabled cleared the faded effect, it only was ever a problem when color was changed by code for whatever reason 🤷♂️
I did that and I still have the error, but the game's running fine, so I'll just leave it.
Restarting unity fixed it.
did you make sure to clear the console? exceptions won't just automatically go away on their own from the console until it is cleared
I cleared it a couple times, but there must've been something behind the scenes still open, since restarting the editor worked. Thank you, I probably would've kept commenting stuff out for hours without that!
I've never attempted to make a save system, but having a hard time wrapping my head around how I could go about it in my situation.
To keep it simple here's one aspect of my game that I want to save and load.
How would I go about saving a List of Classes which have various values that change during the game (ints, floats). These classes are permanent in the game until the player destroys the item.
I want this List to be exactly the same when the game is loaded. Would I have to save each class in its current state. Then on load create new instances of the class, change the values to what was saved, then add it to the List?
Hi, I am loading the .glb 3D model at runtime. and getting this error about material "ShaderMissing; Shader Graphs/glTF-pbrMetallicRoughness" How to get this missing shader and fix this issue? i am using URP.
Make sure the shader is either assigned somewhere in the scene, or in the always loaded shaders in the project settings
It's possible the shader gets stripped out at build time. In Player Settings you can specify "Always Included Shaders", or create a Shader Variant collection.
@cyan ivy @quartz folio Thanks! I have solved this by transferring shaders from Packages to Assets folder.
hey guys, i'm trying to measure the volume of the mic of my vr headset. i've created the needed scripts and when i use the mic of my pc everything works. but as soon as i switch to the mic of my vr headset it just doesn't do what it's supposed to do anymore. it's like it's not picking up the sound of my VR headset mic at all. i'm probably just forgetting a certain setting but i have no clue what. anyone knows whats going wrong?
try using the VR Mic in Discord. Switch to it as the input mic and see if it's picking it up....
it's not picking anything up
Step up a level then. Will Windows/Linux pick up input from the VR Mic?
nope windows isn't picking anything up either. should have included this in my original message already tested that yesterday.
have you setup(drivers/software) your VR headset correctly? Are you sure the VR mic is functional?
Pls can someone tell how to bend my character body using third person view without using animation rigging package with out any plugins
While aiming
yes my vr mic is functional there is another project i've been using in which my mic does work
is that on another computer?
Nope same computer that's what confuses me so much
That's a project I downloaded from someone else tho which is why it makes me think i' forgetting a certain setting
@azure terrace this might sound crazy but reboot your computer and don't open discord. see if your VR mic is working then before opening discord....
I had an issue where somehow discord was keeping my hdmi audio from working with my headset plugged in. only way to fix it was to reboot the computer....
some applications take exclusive access of the mic. i think discord is one of them? make sure discord isn't using your vr mic! it could be keeping unity from being able to access it....
@azure terrace
it actually fixed it
thanks!
I have the most bizzare bug - are there any known bugs around GameObject.InstantiateAsync breaking references inside the instantiated object?
I have tried using it a few times before and i also got strange issues (unity 2022)
issues like?
maybe it's similar
this is my issue: elements test is a freshly created and hand-assembled list, so it's not accessed anywhere at all. First image is the prefab, second is the async instantiated object
when playing around with object order/duplication the things that are missing seem to be changing, but I haven't found a consistent pattern yet, even though there does seem to be one
I dont fully remember but stuff was half broken/missing so probably what you are getting
Did you confirm that it is indeed an issue with InstantiateAsync? Do the references work if you use plain old Instantiate?
(And are you doing any custom editor scripting/custom inspectors?)
Do the references work if you use plain old Instantiate?
yes, I just finished moving my script to use InstantiateAsync instead of Instantiate and it was working before
I do not have any custom editor scripts on the affected script
I also just verified that a list of ints is unaffected, it's the references that are breaking
Are these missing components on children of the prefab?
no - if I go to manually assign the list as it is in the prefab, it's perfectly possible
So these are components on the root object
no - they are components on child objects
and they are not missing on the children, I can freely just reassign them back onto the list by hand
Ok, that's what I asked previously :p
To be clear, it does seem like a bug to me
Simplest reproduction so far, on a UI prefab:
- Create a script on the root of the prefab that has a list of RectTransforms or probably also any other component (tested recttransform, custom script and canvas renderer)
- Create a bunch of different children on said object
- Fill the list on the root object with components on said children (various different children, that's important, sometimes doesn't happen if there's too little children or the list is too small or there's too many repetitions, hard to find a pattern)
- Instantiate the prefab using InstantiateAsync during gameplay
I haven't done much testing, if someone here can reproduce this issue it'd be pretty cool to report a bug
unity 2022.3.41 for me
kinda wish i rememberd fully what i experienced but at the time i did feel like an engine bug so i decided to stop using it.
A shame as my code uses async a lot so would like to make use of it more.
are there no vc channels?
no
but for extended assistance maybe?
🎙️ Voice channels
We will not be adding voice channels. They are difficult to moderate, and also tend to benefit those not willing to put in effort to problem solve and describe their issues. If you are troubleshooting with someone willing to help on voice or video, take it to DMs.
If you want extended assistance, make a thread for people to join
it also cuts off the amount of people that could help you, because not everyone has a mic to chat with
So you joined this server just to check if there are voice channels?
So, you join a server for a product you dont use and say it's shit for not having voice channels, very strange attitude
I think they ask if we think voice channels are shit, not the server for not having them
doubt
hey so can anyone check my script and tell me what's wrong with it? I want an ambulance to come from random direction which tries to passes through the player but before it comes, it should display a waring sign which is blinking for 3 seconds?
not if you don't post the !code, no
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
can you suggest me any Ai I could use for coding? need it for assissgment
The AI is your own brain. Don't use AI for your applications until you are familiar with Unity and coding in general
figured it out
shouldnt create square as gameobject but rather as a sprite in the assets folder
just need it for C#, apparantly my brain is not so smart hahha
if you use AI for assignments, that brain situation of yours is definitely not gonna improve...
brain is a muscle
I tried, I'm learning but I'm kinda stuck so....
That's not how it works. You have to improve yourself and continue learning by doing
Then start basic. Try to follow a tutorial and try to deviate from it a bit with your own approach
figured I would I ask for help
Then, as you go, try adding custom features or playing with the code to see what happends
AI is not going to improve your situation
yeah AI's a trap for programmers lmao
it just makes you worse long term
anything beyond simple autocomplete is ruining your brain further
fine, we're still waiting for you to post your !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Sir, I respect what you are saying and I don't like Ai as well so I'm here, where can I ask again pls tell me
I mean AI is going to severely fuck up your experience with programming in general. You're going to have plenty of unfixable bugs with no way how to debug them
you haven't posted any code that we could even help you with
you haven't described an issue
Please share the code then. See the bot message above for paste sites
not really but kinda
not really like that at all
Should you have coding experience like a lot before unity
ig?
exactly like that
cuz im legit rawdogging I only got like 3 motnhs of experience
i just wanna make a simple superhero game lol
no
Well, there are no voice channels
If you have a coding question, ask it here
i get that lol
Flappy bird hero edition? 
Otherwise continuing this is pointless
yeah smth like that lol
Hey, how do I change the anti-aliasing property of a URP Asset?
I pasted it, can you please check pls
You need to hit save and share the link to us
If you used a paste site
really?
still no
What on earth am i looking at
why you even arguing with me there is literally no point XD
that's html code?
Did you copy the HTML of the paste site??
it's unnecessary
@flint agate Don't save the whole website. Hit the save button on the site instead 💾
Lmfao
like this?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hey, you might have missed the proper way to send code here
this is really unwieldy to read
- Paste your code into paste.ofcode.org
- Press "Paste it!"
- Copy the URL link from your browser and paste that here
use some of the services shown here
instead of just plainly pasting it
There we go
So whats the issue?
It's written below in the paste
// Error is that, the ambulance is not spawing properly and the blinking effect is not working as well and the ambulance should move throgh the player from any direction.///
What's wrong with the ambulance spawning?
I was hoping for a bit more structure, as this is not one but three issues 😉
😭
the code seems... alright? everything should work
you have to specify what exactly doesn't
I expected way worse code
same
This is fine
Describe your issue better
"ambulance is not spawing properly" doesn't tell much
probably some issues inside the editor...
"properly", "as well", "should" are all words, that need to be explained by you to us, so we know what the meaning/result is, that you desire
So the ambulance prefab is ready and so is the Warning sign,
So I want the Ambulance to move to the player but before it appears, it should display a warning sign which should blink for 3 seconds rapidly (Like a warning sign)
As, it can appear from any random location but with a warning sign before
What is happening instead?
I can see code that should do all of that.
For now it is not showing the warning sign, it is not moving or facing towards the player but and that is the problem
Do you have any errors in the console when this code runs?
Show the inspector of this AmbulanceSpawner component
console isn't visible 😢
It looks like it's probably very important
That error is causing SpawnAmbulance not to run
it is for the sound, which is not imp for me at the moment, I just want to fix this error
When you get an exception in your code the code stops running
how can I fix that?
it doesn't matter that it's for the sound
you need to fix the error
either comment out the sound code entirely or fix it
the error tells you
look at the bottom here
reading the full error
it shows you the files and line numbers involved
this is called the "stack trace"
Does anyone know how to implement borsh serialization in Unity?
for those unfamiliar: https://borsh.io
I guess you'd find a C# implementation such as https://github.com/hexarc-software/hexarc-borsh and use that.
@leaden ice thanks
ah, there you go
again, I'm sorry to bother but I couldn't find it... : (
look at the stack trace
if you can't understand the stack trace share it here and we can help you understand it
Is the warning sign a prefab, or is it a gameobject you placed in the scene?
I got it thanks
Not gonna lie, it's not often that I see an error that I've never seen in my life before
'/data/app/~~-blk_O6i4rRxmfamgpQRpA==/com.mycompany.mygame-vFfy7QH-qOt-Oi7GUr9EzA==/base.apk/assets/bin/Data/resources.assets' is corrupted! Remove it and launch unity again! upon launching a build of my game on an android phone
any ideas?
that's a very generic error. It's saying one of your assets files in the build is corrupted, but that could mean almost anything... Unity packs many assets into a single file.
Though I guess maybe in this case since it's "resources.assets" it might be something in a Resources folder?
you need to install LogCat and do a build and run to get more info
I would try just remaking the build to see if it happens again
it does
I have android studio, is that enough?
currently experimenting with a virtual machine
If you're able to connect android studio and read logs from your device then yes it's enough
but it also happens on a real device
That's the same as the LogCat extension in Unity
no, use the unity package and a development build
ah that logcat yea I have it
I'll see if I can get any specifics from it
ok it seems like a Resources.LoadAll call is broken for some reason
can you post the exact code
I wonder if that has to do with code stripping
I just accidentally found I can do something that seems quite odd
for(int i = 0; i < _cells.Length; i++)
{
(int x, int y) = Get2DCoord(i);
_cells[i] = new Cell(x, y);
}```the Cell is able to read the x,y value in the tuple, even though I havent done something like `(int x, int y) myTuple =` beforehand
I'm 99% sure it IS! Soo, a new question - is it possible to add [UnityEngine.Scripting.Preserve] to all classes deriving from a class, without going through them one by one?
that'd save me some headaches
that is correct, it's called variable inference
ah!
this is tuple deconstruction
hammer to crack a nut, you can add it to the assembly
all the relevant scripts just so happen to be in a single assembly of their own! How do i do that exactly?
wait one, let me find an example
[assembly: UnityEngine.Scripting.Preserve]
just add it to one class
tried adding it to the base class, but no luck
odd, because that's exactly what I use
#if (!DEBUG)
[assembly: UnityEngine.Scripting.AlwaysLinkAssembly]
[assembly: UnityEngine.Scripting.Preserve]
#endif
It can't be inside of a namespace, it looks like
yes, before namespace
ah, should've said so!
I figured it could live anywhere
It looks like the "conventional" thing to do is to create a script file whose sole job is to hold assembly attributes
pardon me for trying to help!
it would be a bit annoying to have attributes in totally random places in your code
I appreciate you ^^
But that didn't seem to have solved the issue...
still the same error :/
So what is the LoadAll statement which is failing
It's trying to load ProjectContext, it's a zenject thing
it worked for a long time, and it works in the editor
zenject not my thing
at a guess there is a deserialization failure happening somewhere
Does anyone have a squarerace game?
not a code question #🔎┃find-a-channel
Not sure if that's a unity question at all
have a squarerace?
i presume they're talking about this kind of thing -- which is, indeed, not a Unity question
bro wants a turnkey project
A turnkey project is like a framework, you use it to create a game based on it's structure
a turnkey solution ™️
sorry, read wants as whats
(typo was corrected)
'Thrilling Racing with Colorful Squares' sounds like something for my 3 y/o grandson
dumb question, how do I subscribe to a teleportation event? I 'm trying TeleportationProvider.beginLocomotion += OnMyTeleportBegin and getting an error that 'no overload matches delegate'
what is beginLocomotion params expects ?
so what are the declarations of the event and the method
@regal compass Do NOT DM people without their consent
You subscriber needs to match the event delegate type
You have to look at how beginLocomotion is defined and make sure OnMyTeleportBegin matches the delegate type
Turkey is actually a type of bird and also a country
lol
we were talking about turNkey
I'm just messing around :P
the turkey solution
it's an Action.. I guess I'm misunderstanding the purpose.
Turkey is also probably all the code you write, just messin with ya, lol
System.Action is a delegate type that takes no arguments and returns nothing
Therefore, anything you subscribe to this event with must match that.
Action means:
- void return type
- no parameters
You are seeing the "no overload matches delegate..." message because you do have a method, but none of its definitions are correct
event Action<string> OnSomething
OnSomething += SomeMethod
void SomeMethod (string myStringInput)
example
unless you have nothing for Action<T>, then don't put nothing
(and yes, if it's actually an Action<string> or an Action<int, float, Foo, Bar>, you'll need a method with the appropriate number and type of parameters)
public event Action<LocomotionSystem> beginLocomotion; in the XRI provided LocomotionProvider.cs
I guess I'm not understanding how to set the signature in OnTeleportBegin to match the LocomotionSystem type
so your method expects LocomotionSystem
If it's Action<LocomotionSystem> then your method needs to look like:
void OnMyTeleportBegin(LocomotionSystem param)```
-_- I've been using a custom event bus and forgot how actions were constructed... thank you!
your IDE can also probably generate the correct function if you prompt it
gotcha, thanks all
I would probably only set it when something changes, to minimize GPU bandwidth usage. Not sure if that's really an issue tho.
I'm pretty unfamiliar with how costly it is to update materials tbh
I'd imagine it takes some resources
Does it work without issues?
Note that this is not compatible with SRP Batcher. Using this in the Universal Render Pipeline (URP), High Definition Render Pipeline (HDRP) or a custom render pipeline based on the Scriptable Render Pipeline (SRP) will likely result in a drop in performance.
We don't know where isScaleChanged and isPositionChanged come from, but those are likely false here
Place a log there and see if its getting called
Do you set the bool(s) to false anywhere else?
Do some debugging to see if things are getting called/changed like you expect them to
I don't see anything wrong in the code snippets that you showed
Maybe the issue is that you are doing two SetPropertyBlock calls?
No idea though, just guessing
If you comment out the whole if(ísScaleChanged) block, see if the position change works
I get this error periodically and can't track it down. I suspect(?) it's an editor bug but I'd like to ensure that I don't have any risk of game crashes for something I'm doing.
(can't repro this consistently)
6000.0.13f1 - so I could probably update my editor version but.. that's a hassle, so if anyone knows a more obvious fix, ❤️
Yes, that is an Editor bug however, I would question the attitude of someone who places 'hassle' over getting it right
Well, if it's a "me" bug, that takes me just a little bit of time to fix. If it's an editor bug then we have to do a coordinated editor update across the project and team.. which isn't something we aren't used to, but it isn't something we want to do often.. ideally just a month or two before we launch a game so we can ensure it's stable.
"pragmatic time use" is probably the phrase I'd use
you are on 0.13, the current version is 0.33, nothing is gonna break and Unity are notorious for their crappy dev-ops methods
i got this weird bug and dunno how to fix it
basically it says the enemy has reached the end of its waypoints when it doesn t have reached the end yett and don t know how
Paste the code that you're trying to delete the object. Seems like you're trying to delete a prefab instead of the object (copy) you made from it
Why are you checking if the gameObject.scene.IsValid()? you don't need to do that? just delete the game object
)