#archived-code-general
1 messages ยท Page 371 of 1
And then just divide by 100 when i need the value
You can consider each one as 1/100th of a unit. Just convert as needed when multiplying or displaying it. But store it in a long or int
Huh ok
THAT EXISTS? I was looking for something like this and never found it. Lmao, thanks. Just wondering, if I want to determine all of the triangle index would I still need to iterate through all of the collision points, or is there some mass version of that function since clearly I missed stuff in the documentation. And on that note, I really gotta get better at reading docs
ive never really looked into doing a ton of raycasts at once, so im not sure about that part. i know theres something related to jobs about that.
and yea i assume you would iterate through the contacts and do a Collider.Raycast for each one.
Ok cool, thanks for the info.
position problem; I did the advancement process by adding the spline position to the vehicle position. but as I said before, I am chasing this vehicle. when I get in front of the vehicle. it should continue on a path that is not closed to the left and right. it should turn in reverse if necessary. it is quite suitable for predetermined fixed movement routes, but not a route system, but a system such as a rail is required for escape. it should only move on the rail. the escapes will change completely according to the scenario of the game.
!code please
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ 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.
the character stops even though the joystick does not return to its normal position, and also the character follows the mouse position/pull (the further the pull, the faster the movement) how to fix?
PlayerInput:https://hastebin.com/share/ikeqisevuj.csharp
Player:https://hastebin.com/share/inevinukap.csharp
UiCanvas:https://hastebin.com/share/efevafuful.csharp
Does anyone know how to fill in a script with my 3D Graphic modeling, so I can play my character?
I know how to do 2D, but not 3D.
I make 3D Graphics.
Im not sure your question makes sense, are you asking how to write a script that spawns a 3D model instead of a 2D sprite? What code do you have already?
I want to add my player models to an asset with stock player action scripts.
I want to use the Rotate method to rotate around an object locally can anyone help?
Hello, I'm trying to make an aiming system where instead of the player just point and clicking where they shoot, they hold down click and this 'aiming cone' appears, and it sweeps from left to right at moderate speed, the player has to let go of the mouse button to take the shot when the aiming cone is lined up with whatever they want to shoot.
But I'm not sure how to go about it, because if I want to rotate the aiming cone it will do as shown in the video. I want the top to stay at the player's feet and just the bottom bit moving from left to right if that makes sense?
it helps if you refer to the docs
https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html
i cant use rotateAround and Space.self together
need to figure out how to use rotate method to make it work
so dont use rotate use transformpoint instead
yes, use transformPoint and RotateAround
can you help me with my problem
do not ping people into your conversation
sorry
how would i do it using Rotate and including Space.Self into it
you wouldn't. Rotate is not a movement method which you need to have to rotate around an object
Does anyone know how to solve this? So the robotic character works at a player character? Most poses created.
i need to find a way to use Space.Self but that doesn't work with RotateAround
If the rigs are the same, you should be able to set your Animator controller to the one in your screenshot, if you have variants of it you can use overrides, for example public Animator anim; anim.controller = ...;
Know any links I can look at to do this manually?
Or can someone school me share screen?
Ah, just read your assignment. I think you are misunderstanding it.
use RotateAround to rotate the camera around the planet and use Rotate (Space Self) to keep the camera facing the planet
the part of the assignment where they say "it may go wonky after awhile" might refer to the distance slowly changing over time using RotateAround. I think i read about someone else having this issue, though dont really use that function myself and havent had it happen to me.
If that is the issue, you can fix it by getting the direction (Vector3) from planet to camera, normalizing the vector, then scaling it to be the length you want. Basically always controlling how far it is from the planet
MainCamera.transform.RotateAround(mars.transform.position, Vector3.right, -30f * Time.deltaTime); MainCamera.transform.Rotate(Vector3.right * -50f * Time.deltaTime, Space.Self);
Is it possible to have a Action in an interface? Basicly I have a skillTrigger interface and would like to inject the Ui elements with an subscription to the timer. Kind of stuck on the idea to use a delegate or action
i think that should be right
Guess there should be other smart solutions around the problem
that transform.Rotate looks very wrong, and doesnt seem to actually consider looking at the object. Im not sure if you're restricted from using certain functions for your assignment, but this would solve looking at the object https://docs.unity3d.com/ScriptReference/Transform.LookAt.html
Camera.main.transform.LookAt(mars.transform); i have this outside the if statement
it works alri just when it gets to the top it does like a 180 and then back to viewing it
maybe you want to just use a base class instead? interfaces cant have instance fields
Hi been using IDragHandler with UGUI until I realised it does not care which mouse button is used to drag!! This is not helpful, anyone made it limited to left mouse button?
you shouldnt need both lines, just LookAt or Rotate. But your Rotate is wrong right now, you'd have to do some math to get the eulers you want to rotate it by. Or do quaternion math to set its rotation
we haven't done quaternion but i think its ok now
Yeah thats the route im going for right now, it is a bit messy though. So right now im getting the interface with getcomponent and doing a seperate getcomponent for the base class
and they are both effectivly returing the same object
Can you do something similar to "where T is" in a interface to somehow force it to implement the base class
im not sure why you have an interface and a base class, you just need one from what youve described above
I guess thats true, I do have more than one interface now but could probobly merge those
with the base class that is
that would apply to generics, you cant limit what implements an interface
yeah thats what I thought
you can use an abstract class or base class - only use an interface if you really need to
But i guess a abstract base class or something like that then
I tend to rather do interfaces than inheritance, feel that its easier to structure
but in this case I think that will be the only way
yes that was my initial suggestion. base classes if you need to have some fields associated with it, and then you can still do that subscription you mentioned in the base class
not sure why but whatever works best!
Thanks for help, always great to get input
You can also set the controller from the inspector if you dont need to update it by code: https://docs.unity3d.com/Manual/class-Animator.html - assuming you have a prefab with an Animator component attached
why are tags strings and not something more optimised and how can I have an inspector for one?! They seem problematic
if you're on Unity 6 there's the TagHandle struct you could use instead. you do still need to use a string to get the right handle
not yet - found Cinemachine has inspector handling for selecting a tag at least!
can anyone give a script which manages photon multiplayer system for reference? preferably with audio chat if possible
i need urgently ๐ญ
We dont do handouts here
Besides multiplayer is extremely hard to implement I dont think any of us just has that lying around
Multiplayer is not just a single script, its a large and involved part of online games, and there isnt usually a "plug and play" solution you can just drop into a project and have it work, every project is different - however Photon does have documentation and tutorials, which may be a good place to start
Hello everyone I am currently making a game as a programmer and I wish to learn to make tools to make it easier for other people (non-Programmers) to work on the project, but I dont know where to start. If anyone has leads that would help me a lot.
Editor scripting is something to look at:
https://learn.unity.com/tutorial/editor-scripting
I'm using SetPixels on a texture I'm generating on start, I animate the colors (every frame...) and it works fine in the editor, but when I build to android, I just get the pink no texture color. It seems it's not allowing me to set the texture? I went through the documentation but couldn't really find anything. An ideas what might be wrong and what to explore?
can you share the code that does this?
Sure thing
using UnityEngine;
public class ExampleScript : MonoBehaviour
{
int tsize = 128;
Texture2D tex;
Color[] colors;
float elapsed;
public void Start()
{
tex = new Texture2D(tsize, tsize, TextureFormat.RGBA32, false);
tex.filterMode = FilterMode.Point;
colors = tex.GetPixels(0);
GetComponent<Renderer>().material.mainTexture = tex;
}
void Update()
{
elapsed += Time.deltaTime * 0.5f;
if (elapsed > 1f) elapsed = 0.0f;
for (int row = 0; row < tsize; row++)
for (int col = 0; col < tsize; col++)
{
colors[row * tsize + col] = new Color(0, elapsed, 0);
}
tex.SetPixels(colors, 0); // mipmap level 0
tex.Apply(updateMipmaps: false);
}
}
It's the unity example with some modifications
I tried adb logcat but I don't see any errors
it might be a problem with the material or shader rather than the texture? that code looks OK, and the empty texture if it's not being set properly is grey not purple iirc
purple usually means no shader
Yeah, I can take a look at that, need a specific shader for Android?
not usually, are you using URP?
I believe so, yes
can you check if it's using a URP shader?
probably worth trying to assign a basic URP material instead of whatever's there and see if the problem persists
Actually, it doesn't have a material assigned, I guess it just generates one from whatever I'm doing there in the code
well that code isn't doing that so i don't know ๐ if it works in editor, what material is visible on the renderer when you press play?
I just assigned a random material, let me try building
Yeah, that seems to have been it. The editor would generate the material to make it work but on android I have no clue what was being generated. Now that I assigned a random one, it's working
I'm getting 120 FPS on a really good android, calling set pixels every frame
I have to test on lower end devices but this might be viable. It's only 128x128 though, gotta see if I can bump it up
Can I populate an array/list with empty?
like if I want to store a game object on the 6th place in an array and have the first 5 just be nothing, is that doable?
Sure, just Add(default(T))
where T is the type in your list
oh cool, thanks :)
but sounds more like you just want an array at that point
would an array make empties if i were to store an object on the 6th place?
An array sets all indices to their default for whatever you have
I.E int array would all be 0, array of some class (monobehaviour) would be all null
so what youre saying is, if I were to add a gameobject to an array, in the 3rd place, the first 2 would just be null, and could be filled up later?
yes
oh its that simple
and if i were to move the object to another position in the array, there would be no problem with that either?
correct
nice
Fixed size = array
Dynamic size = list
oh would i have to set the size beforehand?
Yeah you need to set the size
ok, fair enough
But since the exact index is important I assume that you have some restrictions on that size
Just so you don't have a size 2000 but only one index is actually used
Would those transformations be correct? cluster is the parent object (Im trying to make transforms based on rigidbody position and rotation rather than transform's)
public Vector3 InverseTransformPoint(Vector3 point)
{
return Quaternion.Inverse(transform.localRotation) * cluster.InverseTransformPoint(point) - transform.localPosition;
}
public Vector3 TransformPoint(Vector3 point)
{
return cluster.TransformPoint(transform.localPosition + transform.localRotation * point);
}
public Vector3 InverseTransformDirection(Vector3 direction)
{
return Quaternion.Inverse(transform.localRotation) * cluster.InverseTransformDirection(direction);
}
public Vector3 TransformDirection(Vector3 direction)
{
return cluster.TransformDirection(transform.localRotation * direction);
}
(cluster.TransformPoint etc are custom methods that work with rigidbody and are working correctly)
I have a selectable component, but I would like the transition for a right mouse button press to behave the same as a left. What's the quickest way to accomplish this?
hello
i have a problem with move towards
it works one every mob in my game but not for one boss
i tested it
compiler goes to this line
and speed * delta time is greater than 0
i lso chcked player.position
and it works correctly
someone know where's the problem?
should probably check the variable speed especially if it's serialized
i want to buy an old account for playstore
it can be empty with no games
but i just want it to allow publishing games without the new policy of 2 week testing
if anyone is interested let me know
we can also trade i've a new account (i didn't know this 2 week testing policy came)
if this is not allowed in this channel or this server, i'm sorry can delete my post
if this is not allowed where should i go to do this?
So I was planning to use a tweening library to smoothly edit timeScale after exiting the main menu. However, the tweening library would stop working because I set the timeScale to 0 when entering the pause menu. Is there a specific timescale used only by phsyics or do I have to set every rigidbody on my scene to static? (Note: There aren't that much rigidbodies)
does whatever tweening library you are using not support using unscaled time?
ok just found about .setIgnoreTimeScale(true); ty
Question for yall, Did unity change something with how you can assign things in the inspector? I am fairly new to unity and only have real experience on the latest public release, but following older tutorials and looking at packages I see that a lot of them will use the component attached to a gameobject as a variable for prefabs, for example in this code:
[CreateAssetMenu(menuName = "Impact System/Play Audio Effect", fileName = "PlayAudioEffect")]
public class PlayAudioEffect : ScriptableObject
{
public AudioSource AudioSourcePrefab;
public List<AudioClip> AudioClips = new List<AudioClip>();
[Tooltip("Values are clamped to 0-1")]
public Vector2 VolumeRange = new Vector2(0, 1);
}
With the use case being you create a prefab with a gameobject that has the AudioSource component. However you can't assign a prefab to this variable because it expects a AudioSource not prefab, but clearly in the tutorials and use case of this that shouldn't be the case. Generally want to know if this was something that has changed and I should be converting these to generic game objects to use them, or am I doing something incorrectly?
This is how it has worked for a long time. when you drag a prefab (or any gameobject) into a slot that expects a component type, it will grab the correct component from that gameobject
Thats whats I figured, so does that I mean I do need to be converting the scripts like this:
public AudioSource AudioSourcePrefab; To public GameObject AudioSourcePrefab;
Then be sure to pull the component out of the prefab when i need it?
no, the first is the more correct option. it will get the correct component from the object you drag into the slot. You almost never need a variable of type GameObject unless you need something specifically on the GameObject class and don't need to use any of the components attached to the GO
Oh so you can drag the prefab into it, you just can't select it via the variable selector thing (the bullseye part)
yes, you can drag a prefab into the slot. if it isn't showing up in the selection window then make sure you have it set to the Assets tab rather than the Scene tab. if it still doesn't show up, it's likely a bug
Does anyone know how I can disable this?
disable what, the intellicode suggestions?
Hi guys! I was trying to optimise my enemy detection code. I'm developing an RTS type game with a multiple units across the map. Currently I'm doing detection by running a Physics.OverlapSphere on a large radius every 3 seconds for each unit but It seems like this is a bit taxing and I wanted to make the checks more frequent than every 3 seconds. Is there a better way of doing this?
I figured out how to. But now whenever I try to make a new line and type, it puts the new line back on the other line
I don't know how to make it stop doing that
i have no idea what you mean by that
hold on
So like with this I tried putting the line below but as soon as I completed it with a semicolon, it put it back on the line above
check your style settings
Have you tried using the nonalloc version?
I haven't heard of this
The docs for the OverlapSphere even suggest it because OverlapSphere will allocate
https://docs.unity3d.com/ScriptReference/Physics.OverlapSphereNonAlloc.html
busy struggling with how to go about this but how could I have an NPC with a navmeshAgent be hit by a vehicle with a rigidbody
Trying to get this working with ragdolls
Tried adding a rigidbody with isKinematic but that brings the vehicle to a halt when the collision takes place while setting isKinematic to false
Interesting! I'll give it a try thanks
Kinematic bodies dont respond to forces. If you want a navmesh agent with unique movement, just take the path and apply that to a rigidbody
Dont actually use navmesh to control it
oh so have the navmesh calculate the path and move the rigidbody along the calculated path
Yes, if you're relying on the actual physics collisions then AddForce towards the next position in the path should be fine
thanks for the advice
tysm ๐
so im making a moba-like item system in my game, where you have items you character can buy that change how your character works, like for example having a different attack range every 3 attacks, considering im going to have dozens of these items, is there a way to implement this without just making if statements for each relevant item in my combat script? i cant think of any
What part of this would require a bunch of if statements in the first place? Your item implementations should handle this logic and call functions to adjust the player as needed
Most items dont just increase stats and have special passives that generally add more complexity to your abilities, for example, one of the items I have increases all damage of physical abilities by 15. So I'd need to put an if statement if the item is bought or not, and then apply this buff
what's the relationship between MonoBehavior's OnGUI's repaint event, Update(), and camera.Render(), if any?
do some of them trigger each other, or are they all completely independent from one another?
for context, I'm setting up a camera to only repaint when necessary (pretty much exactly how unity's scene view works), so I've got a disabled camera where I'm manually calling Camera.Render() whenever it's needed
but I'm not 100% sure how these interrelate, if I should do
if(guievent == repaint && cameraDirty) cam.Render();
or if I should put this check in Update() instead, and how that affects the OnGUI calls/drawing
I understood this already, but again the items should implement this functionality, maybe through a base class or interface. Your inventory shouldnt be checking what items it has in such a way
I'm not sure on how to do that
How do I control a cinemachine camera system where I want to be able to set the position of a camera (say, when the user scrolls up/down with their mousewheel)? Do I need to create a "to" camera anytime the user scrolls their wheel and then set that one active (so cinemachine does the blending)?
My understanding is that OnGUI happens whenever a UnityGUI event happens... which is any of these things: https://docs.unity3d.com/ScriptReference/EventType.html
As far as I know, that doesn't include Update
But I also haven't used IMGUI in a while.
Oh wait - this one says it happens each frame so there's that https://docs.unity3d.com/ScriptReference/EventType.Repaint.html
so, it says "One is sent every frame", I'm guessing frame here means Update() unrelated to rendered frames from cameras, right?
So each frame there will be 0-n "other events" followed by a repaint event
Yeah that sounds right to me
Does IMGui ever render to a camera? Or is it always in "overlay" mode?
the runtime OnGUI I'm pretty sure is always overlay mode yeah
the editor has a bunch of local OnGUIs
(moved to #๐ฅโcinemachine )
Hi guys! anyone have experience with PID controllers? I created a physics based movement controller and I'm using them to modulate torque to achieve a target rotation.
The idea was if quadrotor drones can do it in real life, then I certainly can do it in unity. I've attached the important bits but I'm not looking for a bug fix, I'm thinking I'm missing something completely about my strategy and I'm hoping someone can point me to the right tree to bark at.
to summarize my current implementation (which works great actually, I just feel there MUST be a more elegant way)
- determine target rotation quaternion
This is the easy part - determine the angle, and axis around which you'd need to rotate, to reach the target rotation.
again I think I have a pretty good handle on this, although I still struggle with gimbal lock with my specific code. - determine desired angular acceleration
This is where I need help. I think first I tried just one pid controller for torque around each axis. I also tried a single controller for torque from the angle difference between current and target. both of those resulted in oscillation around the target rotation. What I finally landed on was this:
float angleCorrection = rotationPIDController.Update(0, angleInRadians, Time.fixedDeltaTime, true); // I had to alter the PID code for this case to make it work. This is because the error in this case will always be positive.
Vector3 omega = rotationAxis * angleCorrection;
Vector3 localAngularVelocity = transform.InverseTransformDirection(rb.angularVelocity);
float accelX = AVPIDX.Update(omega.x, localAngularVelocity.x, Time.fixedDeltaTime);
float accelY = AVPIDY.Update(omega.y, localAngularVelocity.y, Time.fixedDeltaTime);
float accelZ = AVPIDZ.Update(omega.z, localAngularVelocity.z, Time.fixedDeltaTime);
so I'm basically modulating angular acceleration in each axis. I then take these values and convert them to torque given the gameobject's inertia tensor and current angular velocity using euler's equations. The rest is a 100% physics based movement controller, with all movement done using addforce() and no setting positions! I'm quite proud of it and it'd be awesome to refine this bit and understand it better.
I understand how niche this question is but if you know anyone who you think would have good experience here please let me know!
Is there a way to do raycasts with [infinite] planes? without having a GO with a collider in the scene? I want to get the world position of a click from the user's mouse
Plane.Raycast
perfect, thanks
was thinking I'd need to be making a box collider sufficiently large to cover the whole world :p
I've actually written custom Raycasters with this before and then you can integrate it with the event system easily too
oh? that'd be interesting to me because I was just in the middle of rolling my own drag handler
got some code in git or otherwise public?
Basically just derive from this class:
https://docs.unity3d.com/Packages/com.unity.ugui@3.0/api/UnityEngine.EventSystems.BaseRaycaster.html
Implement the raycast function:
https://docs.unity3d.com/Packages/com.unity.ugui@3.0/api/UnityEngine.EventSystems.BaseRaycaster.html#UnityEngine_EventSystems_BaseRaycaster_Raycast_UnityEngine_EventSystems_PointerEventData_System_Collections_Generic_List_UnityEngine_EventSystems_RaycastResult__
And plop it in your scene somewhere
In your case you basically would just take the mouse pos from the PointerEventData, do the Plane.Raycast, and dump the result (if any) in the resultAppendList
hm, ok.. will have to wrap my head around it some more, but this might be useful .. i think i want a simple plane raycast with some constraints (ie, don't click "off" the world map) but it would be nice to be able to just subscribe to my own events
Hmm weirdly enough I can't even find my project that usesd it right now... I think I forgot what it was called ๐ข
Oh wait I found it
Do games generally run at lower fps in the scene view/game view in the engine? I got a RTX 2070S and Ryzen 7, and when playing a simple game moving a cube around, the max i get is around 75 fps. I already played with settings in the nvidia control panel. originally it was capped at 60 fps, but i uncapped it, and now it goes around 75 fps or so. Would expect max fps for a simple game with just a cube
scene view probably lots slower because it's gonna render a buncha other stuff, depending on what gizmos/etc you have enabled
wireframes, selection outlines, etc
Well the project at this point is basically default 3d setup. Theres just a cube and a few cube walls, all gizmos are default
Oh right I forgot I have this whole Board class... Basically that does a bunch of Plane.Raycasts inside
Cool, thanks PB. Just on my way out to dinner and probably done for the day but have it bookmarked. Expect questions tomorrow. ๐
It looks like you're doing what I'm doing basically already, aside from inheriting from BaseRaycaster
https://hatebin.com/ffvlknhtqb ultimately Board.Raycast does this inside
where _terrainPlane is new(Vector3.up, Vector3.zero)
I'll probably also have to do some trig to get the world position from this float
In my case: public Plane Plane => new(transform.up, transform.position); because these things can rotate
since I care about the position in the unit normal plane - so (x, 0, z)
(and .. maybe weirdly? the out from Plane.Raycast is a float of the distance along the ray.. which.. I'm not sure where it originates from.. the camera position, probably?)
Yeah you're meant to use var worldPos = ray.GetPoint(enter); to get the world position
oh, awesome, saves me from having to write this:
Just note that the raycast will always return an enter value, and it may be negative if the intersection happens behind the camera
so it's often useful to check the result of the raycast
yeah i'll add all that error checking later
should be fine since my camera will always be y>0 but for now i'm just proof of concepting it
kinda works but now I'm gonna have to account for cinemachine moving the camera, which moves the mouse, which moves the camera......
but it's on the right track, anyway
basically i'm tracking the start world position and current world position, and moving a tracking target in the opposite direction, which cinemachine blends to
hm... maybe I could do something wonky like parenting a gameobject with a plane to the cinemachine vcam.. I dunno, maybe I'm getting too fancy and should just do "normal" panning.. ie, drag left/right/up/down and I manually move the tracking target some amount of world units instead of trying to be "diagetically accurate" and letting the user grab the map with a god hand to move it around
I've never liked the feel of games where you click on a tree, drag to the left, and the tree pans further or less than your mouse has moved
Hello, can someone explain a small issue I just got? I have a crafting system that refreshes all crafting slots to check what info they have inside right after crafting something. So I put in a "wood" item, the system shows me recipes that use wood, I craft a table which destroys the wood gameobject and THEN calls the RefreshSlots() function, the code checks the slot in which I JUST DELETED EVERY CHILD OBJECT and says "yeah there's still wood in here". I think that somehow the slots are refreshing before the gameobject is considered deleted and I don't know what to do to stop it other than maybe waiting for a single frame. Does anyone know of a more "elegant" solution? If you need to see the code, do tell me.
Also, chatGPT doesn't see any mistakes with it, so I'm super confused because it works perfectly fine when I have more than 1 wood gameobject in the crafting slot.
Debug first
Sorry, I did debug and it is most certainly telling me that the slot with 0 children has 1 child.
Share code
https://pastebin.com/gk6A3DSK here, these are the two problematic classes
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I barely see any useful logs in the code. Debug log more info. For example, if there are children when you don't expect any,debug the names of the children.
sure, thank you
I've been doing some testing and I am more than sure that the slots are refreshing before the object is destroyed. I think it's a Unity thing because in the code, the deletion is supposed to come before the refresh.
I found this: Actual object destruction is always delayed until after the current Update loop, but will always be done before rendering.
It is, but the hierarchy should be updating immediately iirc.
Anyways, I wouldn't use actual gameObjects for items if I were you.
A list of simple plain classes would do.
That was my original idea, but I screwed it up since I'm still new. I just used a tutorial and have been modifying it since.
Does your item destruction code actually run before refreshing? Did you debug that?
It doesn't. I did debug it.
Thanks for the help, by the way.
I came up with a solution though, I just add a boolean to the InventoryItemScript that says if it should be destroyed or not. I can treat it as if it were destroyed just with the bool.
If it doesn't, then that's the problem, is it not?
Yeah that's what I've been saying.
Then it's a problem with your code. Just make sure that you destroy the items before refresh is called.
For Character Controller, is there any built in or preferred method for having a "Step Offset" for downwards steps, so that the player snaps directly to each step while travelling on downwards stairs.
My solution is just shooting a raycast ray a tiny bit further than player height, if that hits the stairs and character controller reports as not grounded, add extra downwards gravity to make player appear snapping down to the step. Though I would like to know if there's a better solution for this or not.
Use ramp shaped colliders instead of stair-shaped colliders
Right, but is what I'm doing to snap the player to the ground the best solution? A ramp will be the same that by default the player will slowly fall down onto the ramp, rather than being immediately grounded to the ramp (which is what I want).
i cant name my parameters please help it ruind all my code and i am really stuck please help me
not a code question #๐โanimation
I'm trying to make a custom button that holds some extra info. I made class derived from button and added a public variable. In the inspector, all the button content shows with no problem but anything other than that doesn't show
It would be easier to just attach a second/separate script, rather than deriving Button
The Button component has a custom inspector
I mean it was only for reference purposes, I believe I still could call adequate methods in start
private void OnCollisionEnter(Collision other)
{
if (IsStunned)
{
return;
}
Debug.Log(LayerMask.LayerToName(other.gameObject.layer));
// NOT WORKING!!!
if (other.gameObject.layer == LayerMask.NameToLayer("Wall"))
{
Debug.Log("Hit Wall");
Destroy(gameObject);
return;
}
if (other.gameObject == Player.gameObject)
{
CollideWithPlayer();
}
}
Can anyone tell me why this isn't working with the wall layer
what does the log print?
Scratch that I'm a dumbass and left the rigidbody as kinematic, PROBLEM SOLVED
name of the layer it is colliding with but it just wasn't registering the walls
but got it now
i was not asking what it would theoretically print. i was asking for what it is actually printing to the console
nothing
right so then next time don't assume that your condition isn't working. that was misleading because the method wasn't being called at all due to it being kinematic
your comment in the code also implied that the log was in fact working
thanks for the advice, the confusion came from the collide with player actually working, it was just the layer related code that wasn't
how can i somehow test if two intersecting collision trigger lines are perpendicular between each other?
i was thinking of somehow getting the overlapped area and testing if the area is more than that square, and i think using a dot product would be too expensive for something simple like this
Get the rotation of both objects and check if the difference is equal to 90?
Just an idea
use the dot product
float min = 1e-6f;
float dot = Vector3.Dot(direction1, direction2);
bool arePerpendicular = Mathf.Abs(dot) < min ;```
okay.. and looking at the docs i would get the rotation direction with Quaternion.eulerAngles?
wait wtf am i saying
Vector2 dir1 = b-a
Looking for suggestions on how I might handle a "negative light-source". Not an immediate need, as I need to work out a few other mechanics, but I'm trying to model the powerset of a character who can enter and exit a ghost state when no one is watching them. I can do the mechanical part of the entering and exiting, but while in that state, time stops (not difficult in this case) and the world is uniformly lit except for cones of vision, which are opaque. I could just add solid cones, but I want them to be broken up by obstacles. Something like a "negative light" could work, like a spotlight that removed light in its radius and otherwise cast "shadows" by not reducing the light behind an obstacle, but I can't find a way to make Unity do that. Lastly, I'm debating some sort of raycasting and building of an object from quads based on obstruction, but that feels like it could get really complicated really quickly.
Worse comes to worse, I can work on refining the actual time-frozen ghost world, but it would be nice to have a solution to work towards implementing.
Thank you! It looks like it might be a touch more complicated than I initially expected, but challenges make us stronger, right?
Bumping my post - looking for anyone experienced with PID controllers.
any suggestions for saving game progress?
Did you google anything related to this? This is probably the 2nd most popular topic for tutorials
make a POCO class and save that to text
as one who made one of those a while back , this is too true 
using System.Collections.Generic;
using UnityEngine;
public class Fruit : MonoBehaviour, IGrabbable
{
void OnCollisionEnter2D(Collision2D other)
{
if(other.collider.TryGetComponent(out Player player))
{
player.CollectGrabbable(ref this);
}
}
}```
I want to ref this class to a method so I could do is casting for making it such that every IGrabbable can have different functionality, but as you may know we cannot ref this as it is readonly
Why are you trying to ref in the first place? It seems you just need to pass it in as a parameter regularly
{
if(grabbable is Fruit)
{
}
}``` so that I could do this in Player class
Ref or out means you'd be assigning something to the class that calls this code
I'm trying to make a setup where an object has different gun objects (each gun inherits the gun abstract) and I can set them in the inspector. However I can't get it to be visible in the inspector... can anyone help? (I'm hoping for a dropdown under Pistol to let me fil in bulletTemplate delay and speed)
!code and also does Gun inherit from monobehaviour? It looks like it from that inspector. Meaning youd have to make a pistol component and drag it into that slot
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ 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.
ohhh so I'd have to make the pistol a seperate component? I think that'd solve my problem, tysm! and yeah sorry I don't come on here much so i forget the rules sometimes ๐ญ
If you define Gun as a monobehaviour then yea itll have to be a component
Is it better to go for a good script that is well written but takes me a while for my game idea, or a rough script that runs but I can code faster?
option 2
premature optimization kills creative flow
nothing wrong with preplanning though, but if you're going for a quick proto idea get something working the way you want first, worry about optimizations later.. if it needs a refactor at some point, not that bad to do
there are two important principles in gamedev, what navarone said is how you get to a point where you have a fun idea, but once you have that you MUST write everything in a competent and baseline efficient way (not optimized yet) otherwise you will drown in tech debt. You cannot ever afford to make something that is shit because it needs to be done quick. The common advice is to rewrite your game (or subsystem) from scratch after prototying is done, and this seems to be the approach that is eventually the fastest. Primarily because scrappy prototyping gives you information on what you actually need, it helps you understand the problem... and nothing is worse than overengineering a solution because you don't understand the problem.
I was trying my best to follow the practices of good clean code, avoiding repetition, too many if statements or any at all, trying to create functions that were multi purpose with generics. All of that kept time consuming, and pulling away from writing the next script. Would it be best for a rough prototype to not write in such a way, or to keep doing it? I work alone, and I honestly just want to do the job once and good. I know it will all be refactored later for optimization and improving the code, but trying to decrease the amount of refactors is what I am aiming for partially.
you also would be surprised how fast you can remake the project after a rough proto was done, because you already know whats needed and wat to avoid
How do you get a gameobject local up axis?
Is it just transform.up * transform.localrotation?
Transform.up is already local
oh, kk
transform up is not local, that would be pointless
Oops I got confused with the wording
alright so is it just transform.up * transform.localRotation >_>
What result are you trying to get with that? Because im not really sure what you mean by local up axis. Transform.up is in world space. In local space the up vector would just be (0,1,0) wouldnt it?
no, your question is wrong, you dont want local you want world space, and that is what .up is
local up is just (0, 1, 0)
So I have a sphere. I have an object somewhere on the surface of that sphere, where it's up axis is aligned with the normal. I want this object to always be looking "up" along the sphere.
This, basically, if it makes sense.
I have the position on the sphere, so I obviously have the normal. I just don't know how to rotate it to always face "north".
Any tips? @lean sail @cold parrot
it's literally just transform.up
ok so you what you want is your character to face north on the surface of a sphere?
pretty much yep
Maybe this?
Vector3 northPole = theSphereTransform.TransformPoint(Vector3.up);
Vector3 dirToNorthPole = northPole - characterTransform.position;
Vector3 surfaceNormal = characterTransform.position - theSphereTransform.position;
Vector3 lookDirection = Vector3.ProjectOnPlane(dirToNorthPole, surfaceNormal);
characterTransform.rotation = Quaternion.LookRotation(lookDirection, surfaceNormal);```
this is not tested
but... I think it should work
It will freak out when you're directly on either pole, for obvious reasons
I'll give it a try. What's the worst that can happen.
your guy looks the wrong way ๐
hi, I made some very very simple Dependency Injection framework with Attributes, reflection, etc., but I have very stupid problem with it - I don't know how to gather INSTANTIATED AND ALREADY EXISTING objects at runtime inside my scenes in not dirty way, so I can populate them with their dependencies at their creation/initialization, lol
like, all I need is just to make some kind of "scene observer" that could check if Game Object is created and provide it to my DI resolver, but I simply can't get the idea how to make it in simple and semi right way (without static events, polling, etc.), like SceneContext class in Zenject (if I recall class name correctly and what it does, hehe)
maybe someone can give hints on how to make this sort of "scene observation" logic in a robust way?
doomed
I was trying to think and got stuck trying to visualize how the projection would work ๐
Why do you need a "scene observer"?
You can just store the references as you Instantiate them
It just works.
Thanks man.
nice, I was like 80% sure it would
iirc there is a projection matrix that converts the 2D surface of the sphere into 3D carthesian space, i forgot how to do that though, sorry, its probaly just what praetor said in 4x4 form
You might also need to check if that lookDirection is the 0 vector, relating to what praetor said about directly being on the pole
there is no right way to add instances at runtime to a dependency injection container, the pattern is supposed to declare how objects are created and then never changed again. You do not add instances to a container, the container is supposed to create them.
ah, I see!
what you probably want is a service locator
I tried to implement something like this some time ago, but it doesn't work. If you see in the video when the ball is hit fast on the mostly horizontal axis it is as if only the collision is registered (not the script) as neither the animation itself nor speed factors are implemented.
Maybe something like this...cs Vector2 direction = playerVelocity.normalized; Vector2 adjustedDirection = (direction + Vector2.up).normalized;//Down for the top player Vector2 adjustedPlayerVelocity = adjustedDirection * playerVelocity.magnitude; Vector2 finalVelocity = minSpeedVector + adjustedPlayerVelocity; rb.velocity = finalVelocity;where you'd adjust the initial direction by combining with an up or down direction and scaling by the player's speed to create an adjusted velocity. Up being the bottom player and down being the top player.
Do you have fundamental c# knowledge. Collections and stuff ? Lists arrays?
Sorry, I relised pretty fast what to do.
Should of taken down the messege earler
Thanks for trying to help though
It's alright, if you need any further help do let us know.
Does unity have built in support for social sharing?
Like sharing on facebook?
phones have like a menu where you choose on which app to share
I mean that
Looks like there is some support for mobiles:
https://www.youtube.com/watch?v=vTIBel9X3mQ
I haven't tested it though.
Ye I saw this asset but its no longer supported
a mechaninc in my game works in the editor, but when i build it sometimes works and sometimes doesnt??
I will have to manually create platform specific plugins and call them from c#
Sometimes things work differently depending on which platform you're using.
Sometimes no longer supported assets are good enough to be used. Testing it out would probably take less time than implementing things by yourself. But first I would suggest searching for some alternatives.
I would suggest checking out the game logs. Logs will be more detailed if it's a developer build.
the code for the sword:
using System.Collections.Generic;
using UnityEngine;
public class Sword : MonoBehaviour
{
private Rigidbody2D rb;
private GameObject player;
private flip pFlip;
[SerializeField] float throwForce;
[SerializeField] float upforce;
[SerializeField] GameObject sword;
void Awake()
{
rb = GetComponent<Rigidbody2D>();
player = GameObject.Find("player");
pFlip = player.GetComponent<flip>();
rb.AddForce(new Vector2(throwForce, 0), ForceMode2D.Impulse);
}
void OnCollisionEnter2D(Collision2D other)
{
if(other.gameObject.tag == "enemy"){
rb.velocity = new Vector2(0, 0);
rb.AddForce(new Vector2(0, upforce), ForceMode2D.Impulse);
}
}
void Update()
{
if(rb.velocity.y == 0){
rb.velocity = new Vector2(0, 0);
}
}
} ```
fixed it by moving the throw to update
idk why it doesnt work in Awake(), i dont really care at this point
If the player is not found, calling GetComponent will throw an exception, and execution will stop right before you add the force.
Execution order can be different between the Editor and a Build, so this script's Awake might run before whatever script is instantiating the player (if applicable)
Use Awake to initialize yourself, and Start to get references from others. If you follow this pattern, everything will be initialized by the time the very first Start executes
1 Player Health
2 Enemy
I have this, and i dont figure out why when i touch the enemy, the unity crashes
anyone knows why?
or what can i do to fix it
(These are the variables)
You have a pointless while loop there that never ends
oh, i see. Thanks!
Remove the while loop
It was too much stuff to post here
Please check out once you get the time => https://discussions.unity.com/t/unity-transparent-window/1523308
Any hidden strategies for aiming projectiles in 3D top down space? Currently using raycasts from camera to crosshair, but that inherently means most projectiles are being aimed downwards towards the ground. Adding a height offset/any sort of aim assist disrupts 1:1-ness of projectile path to the crosshair location, which I'd prefer to avoid. Is my current implementation just the least worst choice, or am I missing something?
Maybe getting rid of the crosshair for a world space laser sight sort ray?
not a code question, also !collab and dont cross post
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
โข Collaboration & Jobs
depends on the gameplay you're after really. You could easily use the target X/Z but keep for example the y target the same height as player or targets center collider for example
(I overexaggerated the scaling to make it look better when the code is applied and when it is not)
fair, but since these are projectiles rather than hitscan there may not be a target at the point of the crosshair (player leads projectiles). likewise, any sort of height offset makes the projectile go above or below the crosshair location which i'd like to avoid.
what I usually do is , aiming mouseScreenPos to world pos, then do another raycast direction from player to target
if there are none just use the direction but keep the height at player eye level ?
yeah, but that makes it such that the projectile no longer goes to where the player is aiming/the crosshair
in what way ? the aim is the targetpos - playerPos
the crosshair exists in 2d space though... it can't account for the height offset. (well it can but you'd have perform some sort of projection to snap it and wrestle control away from the player)
maybe i don't understand what you're proposing.
teh cursor yes but your raycast hit, is not in the 3D world?
it is, yes, but i'm trying to preserve cursor:aim parity
huh what does that mean?
I use 2 rays for a topdown, as i mentioned, The aim direction and such is done via mousepointer then after spot is found, the player raycasts from weapon to the mouse world point but keeps the height the same as player most of the time
this way your ray is straight and not pointing down from camera to world
the projectile should go to where the crosshair is
but again, i don't think there's a way of doing this practically, so maybe i should just get rid of the crosshair in favor of a laser sight ray
Instead of getting the position by raycasting to the ground there should be a plane at the correct level and raycasting to that plane
idk if this helps give the idea
you see the yellow stays at certain height if its not valid to aim at (aiming at the floor in another room)
Any Math god here? Trying to move an object (object has a life time). If his velocity is 1, the distance traveled will be 1 over one second. Given a velocityLoss parameter, it should shouldnt reach a distance higher than the one in the graph while smoothly slowing down. I'm doing this in shader graph (vertex shader). So far the issue I have is that if I set the speed to 0, it will boomerang back to initial location because position is based on time and speed. Im thinking of applying negative speed over time
Hey guys, if my player has two separate state machines (MovemementStateMachine, CombatStateMachine) and both of these need to affect my animations, do I pass them the same animation controller? Should the animation controller responsible for grounded and airborne states be dealing with combat states too? I'm guessing Layers make sense for overrides, but I've never worked with animations before so I'm unfamiliar with common practices
You can create an AnimatorState class, assign them to your animator states and check at the MovemementStateMachine and CombatStateMachine from within those states and update your animator variables accordingly. Class name is StateMachineBehaviour
hey does anybody know why a fresh script would run errors?
I reinstalled the dotnet SDK and it still is bugging out
Depends on the errors
you have pretty big syntax issue
im going to delete my computer rn
you dont add access modifiers inside a method
yea also you have you declared gameobject in start which prob not what you want lol
i dont even really know what im doing lmao all i know is pythoin and this is like my 3rd daying trying C#
check out the pins in #๐ปโcode-beginner they have good resources on c#
thank you
i just made a new project in unity but when i open it says smth like the project was saved on an older version how do i fix it?
i just reinstalled unity
this isnt a code question
where can i ask?
#๐ปโunity-talk probably and share the actual message screenshot
I'm working on a build tool which should automatically build for several platforms we want. I'm confused on why BuildPipeline.BuildPlayer wants to open a dialog box when it's called for the destination.
Does anyone know of a method of triggering a build from script which doesn't do this and simply lets me provide the output path?
hey there, can someone give me some ressources to look into for hashing and salting passwords? I have close to no clue about encryption and I don't know if the threads I find online are outdated..
this is a good place to start
https://learn.microsoft.com/en-us/dotnet/standard/security/encrypting-data
Do study and understand the theory behind it, but in terms of implementation, don't do it yourself and instead use some mature and well tested solutions.
Things like BCrypt has this all figured out for you, and you just call one function to do what you want and that's it.
(But also not sure why password handling is needed in Unity, since most Unity projects are client only)
wanted to make a project using a RDBMS, as I said I'm still very inexperienced. Should I not connect to the database through the client directly? what's the usual procedure?
No client should have direct access to the database.
local or networked DB ?
for now local, but I guess networked later? (not completely sure what that is)
local is fine to connect direct, networked is not, should go through a backend
I suppose that sounds obvious when you say it like that
I got a huge lack of knowledge in backend, API all that stuff. All tutorials ever teach me about front end stuff. Are there some good ressources to learn about that?
what you will need for that will depend on your backend platform and the RDBMS you want to use
Frontend communicates to the backend via some form of API, and backend then processes frontend's requests and modifies database. What technology you use for backend and the database doesn't really concern the frontend, the frontend only needs to know the API.
want to use MySQL as I got most experience with that
on which OS?
windows 10/11
ok, So C# ASP .Net + MySQL
it needs to be a server not a client OS
yes. (ASP .Net?)
oof. as mentioned, huge lack of knowledge haha
Probably consider something else other than MySQL unless you are locked in with that option already. MySQL is held together by duct tapes, not really what people choose for modern projects nowadays.
well lets rephrase my problem. I want to make an app that manages a lot of things (D&D stuff). users can create characters, stories, etc.. What DBMS should I use, what do i need other than the unity part of my app, where can I learn about how to get it to work together?
You just need a backend that actually handles all the logic, and your frontend communicates with the backend.
How your backend stores data is an implementation detail, it doesn't have to be a database (although you probably do want to use one)
what defines a backend? is that one program? is it a webpage?
thought a backend consists of a multitude of things like react or smth
Nope, and React is frontend.
yeah thats just one name I remembered from some videos
so if my backend would be a dbms like Postgres, wouldnt my frontend need to connect to it directly? or are there some other apps I need to put in between?
Frontend runs on client's machine, like your Unity game is a frontend because it runs on player's machine, while backend runs on server's machine where you have full control. That's about the only difference.
No your frontend should never have direct access to database, and database is an implementation detail of your backend.
Your backend can store data in a database, or in a plain .txt file, it doesn't matter to the frontend, the frontend shouldn't know and shouldn't care.
okay thats good. But what exactly could I use for a backend?
The technology doesn't matter, you can choose whatever you feel like. If you want to stay in the C#/.NET ecosystem, ASP.NET linked above is the gold standard.
Otherwise practically every language can do backend and has their own solutions in their own ecosystems. You can really just choose whatever you feel comfortable with.
whats the data storage problem you want to solve anyway?
thanks for the tip!
my brain
I just have no knowledge about backend.
I know MySQL, but not about good practice in connecting it to frontend and how to encrypt passwords exactly
the thing that works between external services and frontend?
technically backend is just "everything the user can't see"
it does not necessarily have anything to do with web, servers and databases.
I thought it usually consists of multiple other applications or smth. Besides years of comp sci in school and now games programming in uni I only got taught about frontend at all
your frontend also has a backend
what are some things the backend usually does for apps?
its a meaningless distrinction if you think too hard about it
makes sense to me
people just usually mean "backend" is "cloud stuff"
but thats just a common type of backend, not the concept itself
lets say I know to write scripts to move GameObjects, calculate stuff and make classes. However, I know pretty much nothing about external services that people use for apps or cloud stuff
and I want to learn what apps are commonly known/used
so in your case, i'd try to form an abstract model of what backend means (pure theory) and then figure out the technologies for how this theory is applied to various use cases.
is apps even the right term?
do videos about backend in terms of web development also help me? I would guess so
but if you are the developer of some service API, this is also your "app", and your end user is another developer
^ The distinction between frontend and backend is more about what actions you can trust.
these terms are overall not very well defined
backend isn't a concept exclusive to client/server stuff
can you name some specific things one uses to manage a dbms/connect it to the frontend?
Neither am I claiming it to be.
but you're talking a lot about it, so to a beginner it clouds the term (pun intended)
You are still confusing backend with database.
Your frontend connects to backend, backend does its own thing and whether it uses database or not does not matter.
i thought backend would be the service I use to connect the DB to the frontend?
the backend is everything that happens before the data appears on the screen
No, your frontend talks to the backend, that's end of the story.
Whether the backend uses database or not is completely irrelevant, your frontend shouldn't know and shouldn't care.
yes i understand that. I want to use a RDBMS in my backend and I wonder what services I should know about to figure out how to connect that stuff. Is ASP.Net all I need for the first steps?
I'm under the impression that they are building a live service game.
hmm... so the issue is really that "its complicated" and there is no simple answer.
kind of. user can create characters, stories and store all that info across devices
why do you want to build that backend yourself?
simplest way to say it
whats the other option?
playfab
does that do everything?
If it's run of the mill CRUD stuffs, you can expect there are lots of existing solutions that save you the trouble of writing code yourself.
Obviously, you will be paying for that convenience.
yes probably
I guess I'll make it myself. for now my project is just for university and out of fun
it can technically do everything since its just a game-specific framework on top of microsoft azure (which is a generic cloud services provider)
it has APIs for storing any kind of user data. though no relational database (because thats generally not needed)
State of cloud services nowadays: reselling cloud services with some code slapped on, for convenience.
hmm i dont know. I probably want to create the backend myself
well if you also want to make a game, then you dont
its more like an app
whatever it is, you generally have to do stuff that 1000s of others have to do also, so someone has made a service to just do it that you can buy.
so playfab is just the answer?
well, it solves most data/server needs for most non-mmo games.
If your goal is to learn, writing your own backend is pretty valuable. If your goal is to get your product to the market fast, then you probably want an existing solution.
thats what I thought
making a backend for a game yourself isn't that difficult if you don't want it to scale
and if you don't care about security
scale in what sense?
concurrent users
and if i care about security theres no way around purchasing stuff?
if you build it as a single-server, non-distributed monolith, its fairly trivial to do
guess it's all subscription based?
but with that architecture, you cannot scale beyond the capabilties of a single machine
and if you ever want to (not that you ever need to), you would have to rebuild it
Tbf, vast majority of the backends out in the world don't have enough users to even need horizontal scaling.
today people try to sell netflix/amazon scale solutions to people who need just 0.0000001% of that power
you can go very far with a single server
they make pretty big ones ๐
It's a plague when people reach for micro services and all the cloud stuffs when they serve like, 20 customers centralized in one geographic location.
how do I find those cloud solutions?
^ most of the internet runs on that
the rest runs on https://azure.microsoft.com/
Invent with purpose, realize cost savings, and make your organization more efficient with Microsoft Azureโs open and flexible cloud computing platform.
other people often just resell these baseline services with added convenience
thanks much for all the help. I'll look into those :)
on both you can also scale all the way down to a single weak virtual server, for free, to get started
thats perfect
and you can scale that weak server from like 2 core 4GB to 192 core an terabytes of memory
hoooly cow
the only gotcha is that you need to be very very very very careful with autoscaling features
can get expensive quickly if your process boosts to 100% so it can satisfy your while(true) as fast as possible
if you dont want cloud, hate amazon and keep it old-school, i would direct you to here https://www.hetzner.com/
Your partner for system-wide hosting, from cloud to dedicated servers. We deploy the latest tech at the best price in minutes.
these are more low-level offerings, more based on setting up your own servers.
less service-y
You will be very surprised how far you can go with a 5 USD per month VPS. A side project of mine for the longest time ran on a 20 USD per month VPS, and it serves over 300 million requests per month with no issue.
Oracle Cloud has some very generous free tier offerings.
If you are cheap you can sign up for free tiers on all the major cloud platforms and you have a ton of forever free resources you can use for learning/side projects, without paying a penny.
I need my collision triggers to be one-directional, so I tried using a platform effector, but when I do I get an angry warning. Should I just make my own direction check in the OnTriggerEnter?
Or are there other effectors intended to use on triggers?
sorry for the ping, may I ask you which VPS you are using or what you would recommend?
Any provider is fine. If you are just learning and experimenting, use the free ones from cloud platforms.
is cloud platforms one provider or wdym with 'from cloud platforms'?
AWS, Azure, GCP, Oracle Cloud, etc, are all cloud platforms offered by different people.
hell yea
VPS > Cloud Services
also Nakama
Who you responding to?
is there any way I can have 2 of the same named assembly definitions
and have it so they're "partial" ? and get combined?
is there a reason you can't use an assembly definition reference? That's the normal way to do what I assume you want, which is add scripts from a separate folder into another asmdef so they exist within the same assembly
Anyone who knows Rider, can you help me? Rider keeps placing new lines as gaps between code
Settings -> Editor -> Code Style -> C#, probably one of the blank lines entries
I got it, thank you!
Hey everyone. I've suddenly found out that Chronos package has been deprecated. Are there any alternatives to it? Or have Unity introduced any better ways to control time aside from basic UnityEngine.Time? I need a tool that allows me to control multiple different time scales like in Chronos.
looks like it's free and open source, why not just maintain it yourself? This looks super overengineered to me personally though
GetComponent<CharacterController>();
gameObject.getComponent<CharacterController>();
are these two equivalent?
hi, I hope this is the right channel for my question: i am trying to make a player movement controller for a 2d platformer. for some reason the player sometimes gets stuck when moving in one direction and can't continue moving in that direction unless i jump or move in the other direction. what could be causing this? here is the code: https://gdl.space/liridavola.cs
not sure why this is in FixedUpdate
if (Input.GetAxisRaw("Horizontal") == 0)
{
if (IsGrounded())
{
horizontal = Mathf.MoveTowards(horizontal, 0, drag * speed);
}
else
{
horizontal = Mathf.MoveTowards(horizontal, 0, drag * speed * airMultiplier);
}
}
Also never check a float for equality
And you really should add some Debug Logs to see what is happening
is this better?
Input.GetAxisRaw("Horizontal") >= -deadzone && Input.GetAxisRaw("Horizontal") <= deadzone
it's in FixedUpdate() to make sure the player is slowed down no matter how fast the game is running
no, should not be checking Input in fixed update
i should just use the input variable i set in update, right?
yes
but this code is identical to that in Update so I dont see the need for it at all
what do you mean by identical? in update i add the velocity, in fixedupdate i slow the player down if there is no input
I've been adding my game elements (card game) to a scene normally so far without a canvas or anything, and now i'm trying to make the game have some drag and drop features. I'm seeing a couple different suggestions for how to add mouse events, namely: canvas, rayscanning and just using the unity events (which seem to require a collider). Given that this is a 2d card game, is any of these options the clear choice or is there a reason to go for one over the other?
I tried messing a bit with the canvas but it was confusing me a bit with how the scale worked inside it. Colliders seem to work easily but im not sure if that's overkill given i dont actually need any collider stuff for the rest of the game. Haven't tried rayscanning but saw a few people say that it can end up being a lot of manual work
If something benefits from existing in the world, then it usually should be kept as a non-GUI object or use world-space Canvas. Examples of benefits from existing in the world:
- physics system
- depth
- perspective
- lighting
Non-world-space GUI objects are usually meant for things that are: - flat (there is no depth)
- have no perspective
- positioned/stretched based on the screen resolution (e.g. put in the corner of the screen or be stretched on the bottom edge of the screen)
- have pixel-based size
- somehow sorted (I would say it gets rids of so-called z-fighting)
Also, it's worth mentioning, that GUI have some neat features like masking, layout groups or canvas scaling.
If you try hard enough, you will be able to reproduce things usually used in one system in another one. Using world-space Canvas is a way of mixing perks of both systems.
I see I see. I don't have any physics, depth or lightning (though the latter could be nice to do later but maybe I can just fake it since it's 2d anyway). I found a similar open source example online that seemed to do pretty much all in canvas so I might just try that after all. If it doesn't work out for some reason, hopefully refactor doesn't end up being lethal
hmm is there a nice way to reference assets from a static context in unity, both in editor and at runtime, without relying on AssetDatabase in editor code, or Resources at runtime/editor?
explain static context
I'm making a custom Handles.PositionHandle() that's supposed to work at runtime (in my builds) as well as in the editor, and it has dependencies on a few shaders
(and might have some other dependencies down the line)
(I know there's Shader.Find for the specific case of shaders but I have other things I want to reference too)
well you could maybe use streaming assets and webrequest but asset bundles/addressables is made specifically for this
hmmm I've never used addressables, I'll look into it!
how does it handle build stripping?
do I need to explicitly tell unity "include all these addressables" or does it detect which ones are fetched from code from the string directly somehow?
oh boy this generated a gazillion SOs in AddressableAssetsData lol
so I have kind of a weird use case for how I'm building this project, would these file interfere with user's project if I use these in a unity plugin, and they install my plugin?
this seems wayyy to big of a system for what I'm doing I think
I thiiiink the easiest solution is for me to assign to a static field from a unity Object, where appropriate
and then just assume it's been assigned from my static functions 
How do I pass Coroutine as a parameter while keeping its reference?
It seems to make a new reference, do I need ref keyword?
private void ChangeVolume(AudioSource audioSource, Coroutine coroutine)
{
if(coroutine != null) StopCoroutine(coroutine);
coroutine = StartCoroutine(ChangeVolumeOverTime(audioSource, audioSource.volume, volume, time));
}
I want to stop previous corotutine and start a new one, coroutine is a variable in this class, but I have multiple(for each audio channel) so want to reuse this function and pass audioSoruce + coroutine.
no, Coroutine is a class
Coroutine musicVolumeCoroutine;
I meant a reference to the instance of that class then
how do you set that variable
here
I am passing it to this function
You can use ref yes, but I'm not sure that's a good idea.
yeah I needed to use ref
you cannot use out, because you are stopping first, wont work
it works
Yep it works exactly as I want it to work
I didnt know that I needed ref for Coroutine ๐ฎ
why pass it as a parameter at all?
so I can reuse that function
Since I have 3 separate coroutines and 3 audio channels
so I can control their volume over time separately
I could also pass enum and do it this way, but I prefer this way.
Unless there is a good reason to not use it
I don't have a strong opinion, but I can't recall a single case that I've used it despite knowing it.
I have two gameobjects with a float endTimer. There also is a barrier with a proper tag so that I can check*** if a gameobject stays there for long enough***. In CollisionStay, endTimer is += .TimedeltaTime'd. I also have a coroutine. A single gameobject correctly works. However, when two gameobjects stay in the barrier, the second gameobject's endTimer at some point stops increasing. This is very close to my coroutine's executing time and when waitforseconds ends the endTimer correctly works again. Other things are affected by this as well. I originally had a circle count down timer with its fill method set to radial 360. I noticed the circle's fill amount would freeze at a value then continue to increase as soon as the coroutine's waitforsecondsends. Why does this happen?
Update: It happens whenever there are multiple gameobjects in the scene, not just in the barrier. Is this something to do with oncollisionstay?
As far as I know, collision stay work as intended. However, you could try to use Enter/Exit and see if it works. (Just be aware that spawning object or/and destroying might result in one of the two event not being called - I am not sure which one)
Also, if you have an issue, try to remove coroutine. It does not seem to be made for what you are doing. Coroutine are usually fire and forget, not made to track the state of an object.
The coroutine is on a seperate script, in fact I use it to spawn the gameobjects with a delay
Then they seem to be unrelated ? I though you were using coroutine to keep track of the time.
Also, beware that coroutine are disabled when object are deactivated.
Like I said, the gameEndTimer that I += Time.deltaTime stays constant at some value at some point, then increases as intended after the waitforseconds in the coroutine ends
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ 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.
idk how to format my last message as code, I literally mixed English with csharp
If you do not want to be help you can also say so.
Post the code of the barrier, the code of the object in the barrier and the spawning of the object.
Then ask like this, when you respond my last message with !code I got the impression that you wanted me to format something as small as gameEndTimer += Time.deltaTime
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ 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.
I coded to restart the game in many ways, but when the page is refreshed, the objects are still immobilized. Only buttons and sounds work.
I somehow fixed it when I replaced OnCollisionStay with an Update + OnCollisionEnter
Anyone knows how to unlock tile color lock?
Anyone knows if this is wrong (initializing a dictionary of dictionaries)
I think it should work. I'm more of a fan of things that can be edited from the inspector, but doing it from code can be good enough for smaller projects. However, I wouldn't recommend using strings like that, because it's easy to make a typo, especially if someone means to use the same string multiple times. Declaring those as constants will make it less likely for typos (and bugs) to appear.
noted for the strings
but I get a Null Instance Error
so I think the initialization must be wrong somehow
Tested similar code:
var dictionary = new Dictionary<string, Dictionary<string, float>>()
{
{ "test", new Dictionary<string, float>() { { "test1", 1 }, { "test2", 2 } } },
{ "test2", new Dictionary<string, float>() { { "test3", 1 }, { "test4", 2 } } }
};
Seems to work fine. I suggest debugging if SetMineralSpawnProbas is invoked.
Added
Actually, the problem is that i had a method at start which called the dictionary and I think it didn't have enough time to initialize
causing the NullReference
onClick.AddListener(() => GridManager.instance.StartPlacing(buildings.buildings[i])); Any idea why this throws Index out of bounds only when pressed? There is no way it is out of bounds, because im looping until i < buildings.count
Is ScriptableObject messaging as a core of a codebase aka "ScriptableObject architecture" worth it now for any degree?
I never tried it for a full project, but I see some very cool pros of using it, but painful cons too. Like without a lot of editor scripting it can be a huge pain to manage it and a lot of manual referencing these SO objects in Inspector
I'm very bad with editor scripting, so it's my main concern about it and the stopping factor (especially that tooling tutorials is quite rare/outdated or I'm bad at searching, lol)
But, I still wanna try it somehow for one or two projects, because I like ScriptableObjects and the idea of functional ScriptableObjects, not just data holders
It's sad that Unity's Chop Chop is gone into the void, heh
This works actually
the syntax was sound and it was really the concurrent Start() calls in which the 1st called the dict before initialization completion
thanks man for the tip on string constants
I had a typo somewhere I think also
What exactly is SO messaging?
Using SO as middle man for event handling, variable object, etc.
It was pretty popular a long time ago after some Unite talk (2017 iirc) and public Chop Chop project
DateTime dt = DateTime.Now;
string saveDateFormatted = dt.ToString("dd/MM/yyyy HH:mm");
PlayerPrefs.SetString(GetSaveDateSlotName(slot, currentInkAsset), JsonUtility.ToJson(saveDateFormatted));
string text = PlayerPrefs.GetString(GetSaveDateSlotName(slot, currentInkAsset));
Why does it nont return a string, but an empty {} instead?
It's converted to a string, it's not a "date" anymore
You're trying to serialize a string to json?
What do you expect to happen here? This makes no sense
The more repetitive and modular game mechanics are, the more convenient Scriptable Objects are. You don't need to know how to code editor to manage scriptable objects, default inspector is good enough. I suppose custom inspectors could do a good job if you need some extra validation.
Whats the formula for determining the x/y coordinates of a point on a circle?
that is a question better asked of Google
Y = sin(theta) * radius
X = cos(theta) * radius
yeah i realised that just now, I got my answer by searching, thanks!
Thanks!
Hello, I have this problem where when I want to activate my dash/dodge function, it instantly moves the player instead of smoothly moving it forward. Is it possible to fix this?
Here's my code
{
isDashing = true;
// adjust this value to change the dodge speed
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
direction = new Vector3(horizontal, 0f, vertical).normalized;
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDir.normalized * Dodgespeed * Time.deltaTime);
//dodgeDuration += Time.deltaTime;
// yield return null;
yield return new WaitForSeconds(dodgeDuration);
isDashing = false;
}
```
The code is only calling Move one time
If you want something to happen over time you would need to move over the course of multiple frames
How would I go about that?
With a loop in your Coroutine with yield return null, or with Update
Anyone know why my UI sliders onValueChangeEvent, when calling a method, some of them require me to type a value and others don't? In my mind the value that gets sent should be the sliders value....
The one on the left works how I expect but then I set up another and it's expecting me to send a hard value
these are sliders for Hue, Saturation, and Value
you have selected the wrong one from the method dropdown
Theres a dynamic one! DUH. TYSM
How can I find what angle is pointing towards a specific point?
I need something located at point A to point towards point B. How do I find what rotation(in degrees) I need to set the thing at point A to in order for it to point towards point B
Probably easiest to use Transform.LookAt for this case.
https://docs.unity3d.com/ScriptReference/Transform.LookAt.html
Oh, thats easier than expected - thanks! I keep forgetting about Unity's built in methods, that's easier. I was about to implement a formula I found online, but I'll do this instead
well, that produces some unexpected results...
hi! does anyone know how to make it so that when the player interacts with these objects the text comes up one letter at a time? also how to make it so that the player cant move while interacting with these objects? i'm pretty new to coding and i've tried so many times but i just can't figure it out
i want it to be like when you're talking to an npc in a game and the text comes up letter by letter almost like typing and you can skip this "typing" by pressing a certain button, idk if that makes sense but if anyone knows how to or has like a tutorial they can send me on how to that'd be awesome
Is there in C# any diffrence in performance between calling Class.StaticFunction()
vs StaticFunction
?
(lets forget for a second about readability and maintan, and namespacing)
its the same thing
also why are you worried about perf diff in how a function is called
cause i have something to do few milion times
they are the exact same thing
if you have to call something so often would worry about your memory allocations and if you can do them upfront and reuse amung other things and just ensuring you are not doing more work then required
for now im fine with memory just need to care about time that happens so looking for possible adjustments
Assets\Scripts\WagonManager.cs(49,10): error CS0305: Using the generic type 'IEnumerator<T>' requires 1 type arguments
I don't get the issue
what are you using statements
like when we start a coroutine we just use private IEnumerator functionName() no?
(you could show which line is 49 :D)
oh it's the private IEnumerator line
yes i know what are your using statements at the top
add System.Collections
oh okok
I'm doing a game jam rn and they made me move to Unity 6000
it used to be automatically added before
this would have nothing to do with the unity version
but yeah because you only had System.Collections.Generic it was tryhing to use IEnumerator<T> instead of IEnumerator
I mean in 2021 when I create a MonoBehaviour Unity automatically adds those using statements:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
Thank you for the info !
you can change what the defaults are
okok
also doubt it included generic
100% it does
the three statements
I have a few scripts in which I wrote only a few lines of code and would have never changed the using statements
E.g. this from another project
C:\Program Files\Unity\Hub\Editor\2020.3.44f1\Editor\Data\Resources\ScriptTemplates
in that location you can define the templates for the various new script types,
obvisuly adjust the path for your OS and unity version
Okay thanks man :))
Not sure what is going on here ...
Hello! I have a heavy lag spike for several seconds when I spawn 100 enemies at once. profiler says the physics 2d find new contacts is the problem. I don't get it, since I removed ALL possible collisions via collision matrix. What is the fix for this?
tried both kinematic and dynamic rb 2d setting. Same heavy lag spike.(Using Unity 6)
Ask in #โ๏ธโphysics
Show them a screenshot of your collision matrix
Randomly started getting these errors on VS2022. I am 100% sure the TMPro pacakge is installed on the project. It was working fine a couple of days ago but now VS intellisense doesn't pick up these packages. Anyone know why this could be? I'm not sure if its a VS issue only or a Unity issue.
- Show the full error messages
- Are these errors only in VS, or are they in the Unity console as well?
VS only. The intellisense seems to be the one having the issues but other projects don't have the same issue.
any errors in unity?
No Unity errors
Then you just need to regenerate your project files
Edit -> Preferences -> External Tools -> Regenerate Project Files
I tried that already even with built-in packages. It doesn't help
do you have the correct package isntalled for vs support
otherwise re-set up the VS integration
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
Hey yall, I have a menu scene. It can't be loaded at the same time as my main scene because they both have EventSystems and unity freaks out. I have a loading screen scene as well, but how can I tell my loading screen scene which scene to load?
I'm just confused about how I'm supposed to pass data between scenes
unless I'm going about this incorrectly
what most people do is just only have 1 EventSystem in there whole game
its part of the first scene to load, and has DontDestroyOnLoad on it, then never have a EventSystem in a other scene
I'll try that out.
i tend to have a Init scene that loads first and contains all the stuff that lives for the whole duration of my game, like the event system
what else would you put in there? I can think of much besides maybe the global postprocessing volume I have
because that'd be active on the menus and such
would a loading screen be appropriate instead of making it a whole new scene?
my initial thought was having it be part of the menu scene, but I need to be able to use it even when the main menu isn't active
no you don't have to make it a scene but its easier to carry over that way
a DDOL does on its own anyway. Any DDOL is part of the DDOL scene which is seprate anyway
I meant more for like data you dont want destroyed going into a new scene
ah yea that tracks
I assume the gamemanager in the init scene would have a Start method that enables the main menu or something, then?
given that each time you load the game you'll probably want to load into the main menu
can't think of too many cases where that isn't true
thats up to your design , you wouldn't necessarily do it in GameManager but you can.
My gamemanager doesnt deal with menus, thats what my MenuManager does ๐
yeah sure if you plan on having a boostrapping scene
some times its also easier to have a specific prefab that has everything you need and it just gets placed in whatever scene you just loaded and use singletons to destroy any copies
I cant think of what else I would do
you have an init scene that loads first
how does it load other scenes
other than a script that loads another scene on start
it usually automatically goes into the Menu
yea that's what I'm imagining
yeah through a script like you said
if you couldn't tell I'm not a programmer ๐ฅด
hehe its no worries, the upside, there is not really a wrong way to do this. You can approach it however makes most sense to you
if right now your issue is having 2 event systems then you should only have 1 active UI Manager type or just dont carry the second scene w event system
or leaving 1 in each scene is fine, just carry other things in a DDOl scene but not event system
would anyone know why the audio isn't playing? from my logs, it looks like the dsp time isn't updating, but I have no clue why that could be. Even disregarding everything else, at the very least PlayScheduled() should work right?
for context, startBeat is 1, and firstBeatOffset is 0. I already know for certain that TimeInBeatsToTimeInSecs() works
void Update()
{
// Update the DSP time
dspTime = (float)AudioSettings.dspTime;
print("dspTime: " + dspTime);
if (_songPlaybackScheduled)
{
if (dspTime >= dspStart)
{
isPlaying = true;
_songPlaybackScheduled = false;
}
}
if (isPlaying)
{
// How many seconds since the song started
songPosSec = dspTime - dspStart - _firstBeatOffsetSec;
// How many beats since the song started
songPosBeat = songPosSec / secPerBeat;
lastPosInBeat = posInBeat;
posInBeat = songPosBeat % 1f;
if (songPosBeat >= Math.Ceiling(startBeat) + _metronomeTally)
{
if (metronome)
{
metronomePlayer.Play();
}
_metronomeTally++;
}
RhythmInputManager.instance.beatText.text = "Beat " + songPosBeat.ToString();
}
}
public void StartPlayback(float startBeat)
{
// Get the audio source attached to the conductor
audioSource = GetComponent<AudioSource>();
// Calculate seconds per beat based on the current BPM
secPerBeat = 60f / bpm;
// Calculate offset
_firstBeatOffsetSec = firstBeatOffset / 1000f;
// Start music playback
PlaySong(startBeat);
print("playing audio");
}
private void PlaySong(float startBeat)
{
audioSource.clip = song;
float startPos = TimeInBeatsToTimeInSecs(startBeat);
SeekMusicToTime(startPos);
AudioConfiguration config = AudioSettings.GetConfiguration();
float dspSizeInSeconds = (float)config.dspBufferSize / (float)config.sampleRate;
// Set the time where the music starts
dspStart = (float)AudioSettings.dspTime + 2 * dspSizeInSeconds;
audioSource.PlayScheduled(dspStart);
_songPlaybackScheduled = true;
print("startPos: " + startPos + "\ndspSizeInSeconds: " + dspSizeInSeconds + "\ndspStart: " + dspStart);
}
private void SeekMusicToTime(float startTime)
{
int sampleRate = audioSource.clip.frequency;
int samples = (int)(sampleRate * (startTime + firstBeatOffset));
audioSource.timeSamples = samples;
}
Im still a bit confused about how the main menu would operate. It needs to have a button that calls a script, but I need to disable the main menu before I can even load my first level. So it disables the script that it's calling and then breaks itself.
But I also can't have it refrence/call a script or gameobject in another scene
I don't understand what you mean
" but I need to disable the main menu before I can even load my first level"
also why does it matter if its the script from menu scene gets disabled
the main menu is a scene that loads in
it has a button that calls a function from a script
if I disable the main menu scene, it disables the gameobject that has the script on it and then breaks itself
also by main menu do you mean like a pause screen or a level selection type deal?
also - you can and should separate the visual aspects of things from the other parts
so 0 you can disable the visuals and leave the rest alone
ok that's a different story,
So you need to rearrange some things there
Clearly you can't leave the button listener on an object that gets destroyed.
the listener can be on the same object as the button instead for example, or some other object entirely, that doesn't get unloaded
then it's not a problem
if the button gets unloaded nobody can click it
you are misunderstanding
the button unloads when the main menu is unloaded. If I attach the scene loading script to the button it'll unload itself as soon as I call the script to load the scenes
Im still a bit confused about how the main menu would operate. It needs to have a button that calls a script, but I need to disable the main menu before I can even load my first level. So it disables the script that it's calling and then breaks itself.
You said this - which implies that the button is the thing that causes the code to run
it is
Why is that a problem?
You keep saying "it breaks" - which is very vague
be specific
because that script has a coroutine in it that needs to keep running until the main scene is fully loaded, at which point it unloads the loading screen scene.
if I unload the main menu scene before that, then the loading screen never unloads and it's just stuck on the screen forever
Why don't you provide all these important details up front instead of making us guess lol
start the coroutine on a DDOL object
A DDOL singleton that handles scene loading etc is a good idea in general
such a thing wouldn't/shouldn't be directly part of a menu scene
except perhaps as a bootstrapping device
how would I call it from the main menu then
By... calling it?
I thought unity didn't support cross scene references
MyLoadingManager.Instance.DoSomething();```
of course it does
just not in the editor
you can do anything you like in code
static instance will help with that
Have you never worked with the singleton pattern before?
why are you in #archived-code-general not #๐ปโcode-beginner lol
Is there not a coder on your team?
I am my team
start simpler than what you're doing now then
this^
n loading and unloading scene, I didn't even touch 1 year into unity as a beginner
I'm more than a few years into Unity
It's only become an issue because I'm trying to do a bunch of additive scene loading
yeah but coding
instead of just having everything in a single scene
yeah like mentioned async loading and unload scene is not exactly beginner stuff esp if you don't know any of these terms
learn for example singleton pattern and how it can be used. Better overused than trying to jump into overcomplex system
typically need manual loading/unloading scenes for specific use cases , you don't need that here
its just breaking the problem down into steps
i keep my loading screen as part of my init scene so i can display it when ever i want and have it cover teh screen while i unload and load stuff
Anyone?
if someone knows they will get to you
is there a way to change the Image fillAmount value range to 1 to 100 instead of 0 to 1?
just divide the number you input in
image.fillAmount = yourValue / 100
Lemme try this
worked, tysm
when dealing with percentages in code its pretty common to always store them as 0 to 1 values
then simply multiply by 100 if you want to display it to the user as a 0 to 100 number
the math with 0 to 1 values is easier in most cases
indeed prefer normalized values myself
yeah want to scale a value, its just a simple multiplication now
@leaden ice Hey I saw a forum post where you were talking about snapping objects together, which you seemingly had done a few times, do you think adding colliders for the snap zones on top of a snap point to make sense? Or did you usually use a different approach?
Also curious if anyone knows anything that exists that already does that before I start making my own
It really depends on the exact behavior you're going for
In my case I only had one collider per object
iirc
Yeah I guess it can go many ways, was hoping to have minimal tuning to do for each different object since they can be of different shape
I think I'll just go for it and we'll see, it might not be too hard
Hey, is it possible to change volume of audio clip(not audio source/channel) in a script?
AudioClips don't have a volume
change it on the AudioSource
I am using Quaternions for my mouse movement, how would I, through code, make it so the CharacterRotation quaternion faces a certain position? Say I had a gameObject and I want to set CharacterRotation to another variable to make it look in the direction of gameObject.localEulerAngles.x
public void Rotation(Transform character, Transform camera)
{
CharacterRotation *= Quaternion.Euler(0f, MouseX, 0f);
if (UseHorizontalClamp)
CharacterRotation = ClampYAxis(CharacterRotation, -HorizontalClampValue, HorizontalClampValue);
character.localRotation = CharacterRotation;
if (camera)
{
CameraRotation *= Quaternion.Euler(MouseY, 0f, 0f);
if (UseVerticalClamp)
CameraRotation = ClampXAxis(CameraRotation, -VerticalClampValue, VerticalClampValue);
camera.localRotation = CameraRotation;
Vector3 localEulerAngles = camera.localEulerAngles;
localEulerAngles.z = 0f;
camera.localEulerAngles = localEulerAngles;
}
}
I think you want ?https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html
yea LookRotation or transform.LookAt would solve that part of "faces a certain position"
though you should just use cinemachine. that whole part of reading the euler angles, setting Z to 0, and then assigning it back looks very questionable. im not really sure why you're using both quaternion and euler here
I don't know why everyone keeps demanding I use cinemachine. I'm a coder, I want to make my own solutions, to learn
just because you want to create your own car as a mechanic doesn't mean you have to learn how to make a tire from scratch etc.
As a learning experience is one thing. But if you want to make a game, Cinemachine is a huge time saver as it already accomplishes 85% of camera needs out of the box
If you want to make your own solutions to learn, why use a game engine at all? Why not write your whole game in assembly from scratch?
There's always some balance.
๐คทโโ๏ธ no ones demanding anything. im not your boss, doesnt affect me at the end of the day. Everyone talking in this channel is a coder
its a premade solution that works well and has MANY features. and its made better than what you or I will ever create
why not start learning soldering so you can make your own PC?
I guess that's true. I mean I know about game developers who made their own functions for cutscenes before Timeline was a thing, but now after Timeline was released, they started using Timeline
I've used unity for about 6 years now and I've never used cinemachine.
If you prefer to write your own tools, do that.
All using DOTween btw
how might i make this jump mechinic spidermen 2 in a 2d plateform sense
#marvelspiderman2 #spiderman2 #PS5
VENOM GAMEPLAY (DAY, NIGHT, RAIN & SUNSET ๐๐)
Marvel's Spider-Man 2 Gameplay PS5 4K 60FPS (Performance Mode)
All footage is captured on the PlayStation 5.
Thank you for all the support on the recent videos ๐ซก if you enjoy leave a like and sub for more!
THANKS FOR WATCHING!
@leaden ice So I did most of it, only oversight right now is that my snapping colliders are all triggers so that does'nt work, should I just use normal colliders without rigidbodies?
i need help inportng a map
my snapping colliders are all triggers so that does'nt work
I have no idea what a "snapping collider" is?
should I just use normal colliders without rigidbodies?
Almost certainly not
Sorry I don't know what the context of this is really
I made a thing that snaps objects together, each objects has colliders on snapping ends, and when two of those colliders collide the snapping logic happens, rn I'm just having issues with having the collision or the OnTriggerEnter register
OnTriggerEnter requires at least one of the objects to have a Rigidbody, and for the colliders in question to overlap
you definitely don't want to use a non-trigger collider here, since you want it to happen when they're close by, not touching
tyvm, all i needed was rigidbodies
figured out singletons and async loading. Thanks for the help.
hi does anyone know how to see custom event parameter statistics within dashboard!? i see how many tiems event got called but i dont see a parameterthat i pass in !?
example i have a buy event .. that records how many times people bought items right.. i also pass in how many coins got spent but these coins are not showed anyware within dashboard!?
i see it as a parameter uder event explorer but they aint sohwing up in dashboard when i create a report
what are dashboard and event explorer ?
also a post so full of typos is difficult to read, please use a spell checker
Please don't cross post. Your question was being answered in #๐ปโcode-beginner
void Move()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
// Get the player's forward and right direction
Vector3 forwardDirection = transform.forward;
Vector3 rightDirection = transform.right;
// Calculate movement direction based on input
Vector3 movement = (forwardDirection * verticalInput + rightDirection * horizontalInput).normalized;
// Cap the movement speed
float maxSpeed = moveSpeed; // You can change this to your desired max speed
Vector3 desiredVelocity = movement * moveSpeed;
// Apply speed cap
if (desiredVelocity.magnitude > maxSpeed)
{
desiredVelocity = desiredVelocity.normalized * maxSpeed;
}
// Only move if not sticking to a wall
if (!isStickingToWall())
{
// Apply movement
playerRigidBody.MovePosition(transform.position + (desiredVelocity * Time.deltaTime));
}
// If no vertical input, clear the vertical velocity
if (verticalInput == 0)
{
playerRigidBody.velocity = new Vector3(playerRigidBody.velocity.x, playerRigidBody.velocity.y, 0); // Stop vertical movement
}
}
How do i get the player to stop moving when i let go of the movement keys?
is this AI code?
if theres no input, then that desiredVelocity should be the 0 vector. you should use that desired velocity to set the velocity. Using both MovePosition and setting velocity isnt the best idea
Hello. I've recently (yesterday) started to learn reactive programming after watching git-amend video about R3. But I'm usually learn by performing certain practical tasks with GPT or Claude, and since R3 is so recent, Claude have no idea about it (it knows UniRx, but from what I get it's fairly different). I loaded documentation in the Claude project, and it is able to generate working code, but I have the feeling that many of its actions are suboptimal and I have no expertise to evaluate it myself. Reactive programming is absolutely freaking great, I love the paradigm, but it's no use for me since I have barely any idea how to learn it quickly and efficiently. Do someone have any relevant experience in overcoming similar issues?
Maaayyybeee.. ahaha
I'll give that a go soon
Sorry, we don't help with AI code.
No point helping with code that you don't understand in general
How can TMP_Inputfield treat multiple characters as one character, similar to in the Discord chat box with '@xxx', where it is considered as one character and can be modified as a whole?
maybe links in rich text?
https://docs.unity3d.com/Packages/com.unity.textmeshpro@4.0/manual/RichTextLink.html
However, it still cannot be handled as a whole. What I'm thinking is to generate sprites in real-time based on the text to handle it. But I'm not sure if it is an efficient way to do it.
how do you want to separate the text? maybe regex or something
or separate the words by whitespace then process only the ones that begin with @.
no idea what you mean by "handle as a whole" though
For example, the "@lazyboy" in the image can be clicked with the mouse, formatted as bold as a whole, and when deleted, it will be deleted as a whole.
from discord input field
hi, i am using addressables to load and unload some prefabs, i expected it to unload with ReleaseInstance() method...Yeah it works, all the assets that was supposed to be unloaded are unloaded from memory, but something called "UNTRACKED" and "UNKNOWN in native section" is taking up almost same memory space as the unloaded asset...Ultimately the memory is not being freed up, what to do in this case?
Are you testing in the editor?
i built my test project for windows, and tested via memory profiler
It could be that unity just reserves that memory for future use. it depends a lot on how their allocators are implemented. Does the consumed memory keep on growing over time?
it grows a little bit over a period of time with a decreased rate
but my main focus was to free up memory whenever i wish to unload things, but it doesn;t seem to work as i expected
It's fine if it reaches a peak point that it doesn't go over eventually. Otherwise you might have a memory leak.
I see. Might want to post on the forums for a clarification. Unity should be more transparent on what that memory is used for.
Though, it could be some plugin or asset, that allocates memory sneakily.
Are you allocating native memory anywhere in your code?
when i don't load anything, the unknown and untracked section remains low in size...whenever i load, both section grows and consumes memory nearly same as my loaded asset...although my main prefabs and things related to that loads and unloads correctly
Then it could be some code on the loaded objects that allocates.
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
public class PerformanceOnSizeTest : MonoBehaviour
{
AsyncOperationHandle<GameObject> handle;
public string prefabToInstantiateAddressableKey;
void Update()
{
if (Input.GetKeyDown(KeyCode.Q))
{
handle = Addressables.InstantiateAsync(prefabToInstantiateAddressableKey);
}
if (Input.GetKeyDown(KeyCode.A))
{
Addressables.ReleaseInstance(handle);
Resources.UnloadUnusedAssets();
}
}
}
here it is, so simple, just to test, am i doing anything wrong here
Alright, I'll remake the movement script myself. What do you think is the best way to move the player? E.g Addforce()
Just as a test, try resetting the handle reference to null after unloading.
like "handle = null" ?
Also, what I meant is a code on the loaded object that could be running on awake, start or other unity callbacks could be allocating memory.
shouldn't i use ReleaseInstance() ?
You should. But you should also reset the handle reference afterwards.
it says it is a non-nullable value type
Ah, is it a struct? In this case it might be fine.๐ค
So, as I said, that memory is likely not related to addressables directly.
Might also want to read the manual page on memory management with addressables. There seems to be a few important points:
https://docs.unity3d.com/Packages/com.unity.addressables@2.2/manual/MemoryManagement.html
i will look into it, thanks...
but still, isn't there any solid solution to this minimal test scenerio
What exactly does the prefab have attached to it?
an environment package i download from asset store for test
And you're loading the whole asset?
i opened its demo scene, turned everything from the scene to a prefab, then put that into the addressables group
Hmm... I don't think that counts as a simple testing case. A simple testing case would be a one GameObject prefab with a sprite renderer or something.
i should try that way then, i will let you know the result
Completely off-topic but wow whoever made that boat model has apparently never seen one in real life
this time i just used one modified plane with lot of vertex and one material...still no good
before loading the asset -> 169mb
after loading -> 207mb
after ReleaseInstance() -> 210mb
There's a channel for #๐ฆโaddressables with pinned msgs, probably best to be in there, asking and reading the pinned
I am working on a package, is there way to reference actual project code? I know its kinda wrong way around but i kinda need access to "shared" code that is generated.
generator creates files i need to use in package but those files are generated based on Project files and they do reference them.
Put the code you want to access in a separate assembly.
Reference that assembly from your package
But yeah it's kinda backwards and rarely needed
You cannot free a specific asset in Addressable.
If an asset is no longer referenced, indicated by the released status and disabled text in the Profiler module, this doesn't mean that Unity unloaded that asset. A common applicable scenario involves multiple assets in an AssetBundle. For example:
This is one of the reason why you need to make your addressable package correctly.
Question, I have a NavMeshLink with Auto Traverse Off Mesh Link = false (and updatePosition = false), but sometimes (not always) the navmeshagent position automatically teleports to the other extreme of the link.
Why that happens? How can I fix that?
Ok
What the best approach for object pooler class + pooled object and keep SoC?
What I did is:
BallManager holds the ObjectPool<Ball> and some utils method to handle and check all the balls.
Balls instead of destroying themselves invoke an event passing themselves, this event is listened by the manager, getting the ball and releasing it to the pool.
Is it the correct approach?
Sounds fine?
Good ๐
Injecting the pool or the ball manager to the ball to let the ball call the release method would not be good
Hi suppose you have a list of points (Vector2) and you want to get the nearest one to another point. So you iterate through the list recording the closest one. Is there a name for this pattern/algorithm? Also I never did points.OrderByDescending(v2 => GetDistance(v1,v2)).First(); as stackoverflow suggests because I figured it must be slow to sort when you just need to iterate through once - any one do that?
I would just use the first option. I doubt that Linq can be any faster than that
Yes I do, I was just thinking how often I repeat a similar pattern!
Could make it into a helper function
Ye swas thinking this - would be much cleaner
Any tips about how to attenuate sounds given obstacles? I'm not sure if I should throw raycasts from the sound source and calculate how the sound bounces from objects until reach the player. ๐ค
There are packages for this, such as Steam Audio
I think Oculus and other VR devs provide those too
If you wanna do it manually, portal-based occlusion could work
If you go with raycast route then its good to know that RaycastCommand exists. I profiled it a bit in my scene and I started getting performanve benefits at around 100 raycasts, while completing the command immediately. This would ofc be improved if you let it run for a frame before completing
Steam Audio went open source some time ago. Gotta examine it ๐
I was thinking adding a bake process.
In the editor I would divide the world in a grid, and for each cell in the grid I would throw thousands (or millions, not sure) of raycasts towards all directions, and more raycasts from each hit as the sound bounces.
Then I would have a dictionary or something more optimized which maps each grid's slot with each other, and count the amount of rays (taking into account their intensities) that reach this slot.
Thought I would check the Steam Audio. I wonder if it works with FMod which we already use.
Baking sounds interesting too
Similiar to what I did with AI shooting/cover positions
It does have an FMOD integration yeah
You bake AI stuff? Cool
Yeah my maps are procedural so everything else has to be procedural too heh
Generated at the start of the game/scene load
I have also seen people use some sort of pathfinding, such as A*, for audio occlusion
unity at home be like:
What engine/framework is that?
its my own engine lol
im trying to make myself a private engine that mimics the syntax of unity
Cool, so C++/glfw?
yea
funnily enough all i wanted to make in the beginning was Tertis lol
but the project kinda spiralled out of control and now im left with the beginning of a game engine
What is supposed to make it move?
transform vector changing
and move towards
also doesn't work
First off, you should move it via the rigidbody instead of the transform