#archived-code-general
1 messages · Page 203 of 1
transform.position is the middle of the gameobject. Is the distance half the height of that gameobject or less? Then it won't reach
It needs to be longer, or moved down
Is my guess
Oh, I see
it depends on where he put the origin of the transform
Yes
Everything that Aethenosity said, but also, Debug.DrawRay is a good way to debug these kinds of problems.
I normally use Cast to cast the whole collider down, but it is much more expensive
I do that because my terrain can get very wacky
and it avoids weird shit at edges
Plus less precise for things like edge detection. I do a tripod of raycasts
i don’t think it is less precise for edge detection. it’s just different
I mean. It IS less precise. It will detect in a larger area, which by definition is less precision
It works though, don't get me wrong
Wrong. I meant what I said? Precision detection of a tiny area. Well, three tiny areas you can treat differently
specificity has to do with the scope of what you are detecting. Precision has to do with the spread of quantitative information
less precise would mean that it would give you a more variable number
Exactly. Which is why it is precision, not specificity
Exactly what I'm saying it does
i mean… it’s looking for the one point of contact under you
it’s getting that point’s coordinate
And that point could be anywhere in a wider area if it catches the edge of the collider. Less precise
if a raycast hits a rough surface, you could be hitting the wrong point, but be getting an extremely precise measurement of that point’s coordinates
that is specificity
Ok, pedant as needed. Go on with your meaningless and incorrect distinction as needed. Later
🤷♂️
it’s easier to explain with biology maybe. A specific antibody is really good at only hitting the one thing it is supposed to hit, which is like #times you hit what you wanted / total hits
that is specificity
a precise measurement would be when you look at a measurement performed with that antibody, and see how much the number of hits varies. That is precision
if (isGrounded && !Input.GetKeyDown(KeyCode.LeftShift)) shouldn't this be a valid statement? It's not throwing syntax errors, but the if statement condition is still being met when I'm not pushing leftshift
keydown is true the frame you press the button
You are checking if you are NOT pressing left shift with the bang symbol
Yea, I want to check to make sure I'm not pressing it
so that second part is usually true, except for the one frame that you press left shift
Wait, so it's not checking if I'm holding the keydown, only if it's pressed
GetKey is true WHILE it is held down
!Input.GetKey
Ahhh okay
GetKeyUp is true on the one frame you let go
I’m thinking about making an Interface for making Monobehaviours act properly when an object is pooled.
I’m thinking about making IResettable, which is an interface with only public void ResetBehaviour(). This is supposed to just bring back the behaviour to the state it should be at right after Awake, OnEnable, Start are called. Is this a good idea, or is there a smarter way to automatically bring all my components to this state?
sounds reasonable. you'd call it when you return the object to the pool
Note that you'd need to either do a cast or make the pool hold abstract classes that implement IResettable
I would call GetComponentsInChildren<IResettable>(), and call ResetBehaviour on each
the pooling class itself won’t permanently store references to behaviours
an alternative is the way unity's ObjectPool class works where you supply delegates when you create the pool which get run when you get/release an object, the benefit is you can avoid adding an interface to everything that goes in a pool
So I'm trying to figure out how to carry the momentum of the player into the jump, but not allow the player to change the momentum while in the air
Depends on how you're moving. You could do an AddForce in impulse mode for the jump and disable any horizontal movement at the same time if you are using velocity or addforce based movement. With transform movement, you'd need to handle it differently, probably just disable horizontal input and keep doing the horizontal movement in the same direction and speed until you're grounded again
{
movement = new Vector3(horizontalInput, 0.0f, verticalInput);
movement.Normalize();
transform.Translate(movement * walkSpeed * Time.deltaTime);
if (isGrounded && Input.GetButtonDown("Jump"))
{
Vector3 momentum = rb.velocity.normalized;
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
rb.AddForce(momentum, ForceMode.Impulse);
}
}``` This is what I have for walking, and when I jump all movement stops except in the vertical direction. However, when I don't jump and release one of the movement keys the player decelerates rather than stopping all at once
@acoustic sinew Yeah, you are using transform.translate, which is like teleporting small distances. It doesn't give you velocity in the same way, so you can't keep your momentum that way. It's more like you're standing still at one point. Then standing still at the next point. Then the next...
You'll have to just keep translating sideways with the movement you had before the jump, but that would get tricky with the y parameter I guess. Maybe use its own y position in that part? Not sure if that'd work
Hmmmm, so maybe I should not use translate and do .Addforce In those movement directions
If you want to. It works quite differently and it has a lot of considerations.
You'd probably find it a lot more "slippery" than what you're doing now
BUt what's weird, is when I release the movement keywhile grounded the player moves as if it does have momentum
Are you using GetAxis?
For input
Yes
Yeah, that has smoothing implemented. You'd use GetAxisRaw to avoid that. But yeah, not sure exactly why that doesn't carry over to your jump
Probably because of the addforce where you pass in momentum actually
Since your momentum is 0, you are kinda halting it with that call
That makes sense. This gives me an idea on trying something, so brb
I like the feel of adding the force, just gonna have to do a lot of tweeking to get it feeling just right. However the force it being adding in the world axis rather than locally
Fixed it. Changed .addforce to .addrelativeforce
Hey, is there any way to add a tile to a tile palette through script? All I could find was setting a tile in a tilemap
hey guys, im trying to make a car with wheel colliders but when i start the game, my wheel colliders move a bit forwards (which they shouldn't), and when i press W to move forward, the wheels move, but the car doesn't move. also the wheels go a bit under the ground
actually i'll post this in editor instead
i’m trying to neaten up my code, i have 4 if’s, so if (name.containsinsensitive(“”)){
wtv = “”
}
so on and so fourth, im checking if the name contains a word and sets wtv to the word if it does, and there’s 4 words, i check each of them, is there a way to do that but more compact then 4 if statements
put your 4 words into an Array and then loop over that
wordsArray.Any(name.Contains) if you want it even more compact
I've been asleep so sorry it's taken a while to respond. The reason why I believe the problem to be around the coroutine is because the error only occurs when the coroutine should run
The stack trace is clearly indicating that this is an error while drawing the inspector aka Editor for your network variable
it shouldn't affect gameplay
Restarting the editor often sorts this kind of thing out.
Yeah I'll try that when I get on later. The problem with it occurring Is that the script it says is the problem isn't a script I have made or edited
Yes, as mentioned, it's the inspector rendering your network variable
it's a bug in Unity's code
Ahh, thanks for the explanation.
Actually, on this subject.
How should you go about diagnosing that kind of error?
I'm frequently seeing an exception caused by a disposed SerializedProperty. I'm thinking it might be caused by one of my packages.
I have no idea how to track down which property is at fault
I don't think there's a good way other than trial and error. Maybe try to put a breakpoint inside NetcodeBehaviourEditor near the error line and see what you can find?
I wonder if the UI Toolit Debugger could help at all
Sometimes an error creates a very obvious problem in the inspector
like, everything just stops rendering
but this one is subtle
wrong image
Indeed
naturally.
I missed whatever that was 😢
You need to be more concentrated lmao
it happends
i didn't get taught
Looking for some ideas how I should implement my tooltip descriptions. So, currently my implementation for data objects all derive for a Storable type such that they include a Name, ID, Sprite (UI purposes), and a Description. This storable type also includes the scriptable object that is in relations to that specific object.
For my abilities, which also inherit from Storable, can be used directly by the player, or through another means like triggers which passively uses the ability. These passives are linked to my Trigger class which also inherits from Storable, such that each Trigger instance has an Ability instance wrapped inside.
Lastly, I've a Mod class (also a Storable type) which depending on the requirements, will or will not be added to the character. This class can contain an instance of Trigger, meaning that if the player meets the criteria, this mod will allow certain abilities to trigger the ability it contains.
So to break it down: Mod instance contrains a Trigger instance, which contains an Ability instance. All of these classes inherit Storable, and thus all have their own descriptions. Now, that's a problem because since I've all these descriptions, I don't know what to prioritize on what to populate my tooltip with. Ideally I'd populate the Mod description and use that, but as I said earlier, abilities are not* strictly used by triggers and can be casted normally. So, if it's contained as a Mod, it should contain a different description than displaying the Ability info.
Maybe the idea is just separate descriptions and just make it an interface. That's one way I guess. As it is, I'd like to minimize the amount of wording I need to do for everything, but I guess it's just too much mixing and matching that I may just need to populate it all manually.
I hate UI stuff
Interestingly too, a lot of games seem to implement sprites for all their objects even if not used. So that's kind of another thing I'm debating keeping as is because it doesn't make sense for some wrappers to be displayed on the UI.
I would recommend making it an interface regardless. Inheriting from a class for this case seems overkill
is it expensive at all to have an additional trigger collider that touches everything in the game all the time?
So say someone downloads a project of mine, and this project has several options that I have to seperate out with several #defines
Currently, to enable or dissable any one of these, the user has to go to each file that uses the define they are interested in and comment/uncomment it in each file
What is a better/more user friendly way to do this that still allows the #define kind of behavior but can be toggled in a single place easily instead of having to be toggled in 5 seperate files?
Project settings
but that seems like a hassel for whoever downloads my tool
it's in one place
Project settings seems like a hassle?
fair
alright ok I will do that then thanks!
just seemed inconvienant, its more convienant than I currently have, but I wanted to see if there was something more I could do
You can make a custom Editor window to toggle the defines.
you could easily write your own Editor script which directly affects the project settings, makes it that little bit more convenient and accurate
OH!
I completely blanked on the fact that an editor script can modify the project settings... thanks!
Can someone tell me if this is wrong and has an error or right (this is a player wasd movement script
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 5.0f;
void Update()
{
// Get the horizontal and vertical axis values
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
// Move the player based on the axis values
Vector3 movement = new Vector3(horizontal, 0, vertical);
transform.Translate(movement * speed * Time.deltaTime);
}
}
your IDE and unity will tell you if there is an error . . .
and wrong how? did you test it at all. did it work as expected or nah?
ima see
gonn tell u in dms
the whole point of asking in here is to get help in here. anyone can assist. i can easily leave or not know how to solve it . . .
thank you for the good information👍
Does GetButtonUp work with the axis?
hmm, what do the !docs say?
That's what I was thinking, in the Docs it shows "Fire1" as a button, so I didn't know if using the name of the axis would work
just use axis lol
if its an axis you would just check the float
What I'm trying to do is figure out is how to add extra deceleration to my player outside of increasing the drag on the rigidbody
it returns a bool and states it should only be used with action-like events . . .
Starting a Gradle Daemon, 1 incompatible Daemon could not be reused, use --status for details
don't you have a vector2 for inputs? @acoustic sinew
it even says to use GetAxis for any kind of movement behaviour . . .
I'm taking the input from the axis and setting Vector3 value.
if(inputs == Vector3.zero) if(rb.velocity.magnitude > 0.2f) //add more friction
or something like that
maybe you can even swap physics materials
Thanks, I'll give something like this a try and see what happens
Okay this is gonna sound a bit dumb, but I’m trying to create a sliding script in unity3d and I cannot figure out how to even make the character move forward on a button press. I have the WASD and jump movement already set up, but for some reason I can’t figure out how to make the character move forward on a different button
Using a character controller btw
!cs
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
i was just testing the command lol
are you sharing script ?
Hey guys has anyone worked with Qauternions and Euler angles I need some advice… I need to implement a scene where a person can rotate an object along the all permutations of x,y, and z axes and was wondering how difficult this would be
What does "along the all permutations of x,y, and z axes" mean?
Along xy means rotating around the z axis, xz - around the y and yz - around the x. Which is totally doable with transform.rotate method.
That's assuming I interpret your "along" correctly
Yes so it’s just a simple transform.Rotate() it must also be done with a mouse
Like a cursor should be able to rotate it around these axes
How are you defining your third axis?
Not sure I haven’t began to conceptualize how to do it other than I’ve read on some forums this ha been done with quaternions and Euler angles
Is there any way to breakpoint UnityEngine methods? Like Object.Destroy
How can I run a script in the editor (not in play mode) with the goal being to make some modification to all objects in my scene that have a specific component?
how do i make a cinemachine virtual cam follow a rolling ball and not rotate?
these are the current settings
@hearty sphinx I have no idea what a cinemachine is...
Do you have to provide a LookAt transform?
according to tutorials you just need a follow
Maybe worth trying quickly just incase?
@hybrid turtle Have you given any more thought to your issue?
If I'm understanding correctly, you're wanting to rotate on all 3 cardinal axis using your mouse.
An issue the others hinted at was the fact that really your mouse only allows for rotation about 2 cardinal axis, not 3.
(Move mouse up/down for one axis, left/right for another... and nothing for the 3rd axis rotation)
You'd probably have to have some additional input, a toggle of sorts, to allow your, for example, left/right mouse movements to rotate around a different axis when toggled
@vague slate Would setting a breakpoint in your objects OnDestroy method do what you're after?
yes, did it already 😅
making the camera follow the ball seems like too much work, how can i add force to the ball relative to the camera?
assuming the camera is fixed, the ball will always go south if i press S
If you're using the unity physics engine, you can get a reference to the balls RigidBody and call the AddForce method, with some force value
var horizontalAxis = Input.GetAxis("Horizontal");
var verticalAxis = Input.GetAxis("Vertical");
var direction=new Vector3(horizontalAxis,0,verticalAxis);
rg.AddForce(direction * force);
i'm currently using this, but i don't know how i would move it in relation with the camera
Please describe how your camera works
right now i'm just setting it at a fixed position like in the picture
Then the ball will always be moving correctly relative to your camera
oh i didn't think of that
i thought that randomly spawning the ball would change how it moves
and i just need to set the camera correctly
not the other way around
Creating a age old game called BaaghChaal. Need help with coding the logic.
Hey, is there any way to add a tile to a tile palette through script? All I could find was setting a tile in a tilemap
Hello. I have a list with positions and rotations. I need to move the CharacterController around these positions and rotate him. How can I do this?
you could start by looking up how to move objects with CharacterController?
even looking at the documentation for CharacterController will get you someplace
I know how to move objects with CC, but I have a list of positions and I need to move an object by these positions with some speed
okay, how do you move objects with CC?
Move method and some direction🤔
The general algorithm is that you save the first position in the list in a variable as the current target and move towards it. When the CC reaches that target, you change the current target to the next position in the list and so on
It's called "waypoints," it'll get a lot of hits with Google
Hi, I've been trying to figure this out for literally 24 hours, I'm completely new to Unity and coding and is desperate. Please help me...
I've been trying to follow this tutorial: https://www.youtube.com/watch?v=0T5ei9jN63M
🤖 Play Web Version: https://unitycodemonkey.com/unityPlayer.php?v=0T5ei9jN63M
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=0T5ei9jN63M
In this video we're going to make a Health System and a visual Health Bar.
It's going to be a clean and independent class that we can apply to anything like the player, enemies...
These are my scripts
I made sure patience bar is arranged accordingly in hierarchy
But my health bar just isn't moving, does anyone know why?
According to my debug, the bar is supposedly moving, and the patience percentage is calculating accordingly - but the bar itself just isn't moving
any errors
and did you check the localscale of Bar
honestly when it comes to tutorials not working, it's most probable that you missed a step or did not follow exactly
are you sure you're looking at the right Bar
Quite a bit of shitcode now that I look at it. Using an EventHandler instead of a simple Action (since none of the two parameters are used), usage of transform.Find() where a direct reference would have done the trick, and changing the scale instead of a sprite's fill amount
Are all of CodeMonkey's tutorials like that one? Wouldn't recommend then
Pretty much codemonkey is hot garbage
.
Both can be represented similarly, but behaviour tree states have a distinct structure to them and generally come with a common set of control flow states to compose various states. Just looking at something like Behaviour Planner and the Mecanim Animator should illustrate some of the differences.
Which do you think is more suited for the ai of a soldier npc using guns?
Im looking to get something similar to the ai of half life 2 where soldiers can take cover, throw grenades, reloade, do melee attacks and etc.
there is no set answer for this
So both work fine then?
Behaviour trees tend to be more flexible. But I can't recommend any tools. Im making my own and its a rabbit hole
Behaviour trees are great, just very diffcult because unity doesn't have a built in tool
Thanks for the advice yall. I'll take a deeper look into behavior trees. See how it works out.
https://youtu.be/JyF0oyarz4U?list=PLokhY9fbx05eeUZCNUbelL-b0TyVizPjt
this guy has great series on these subjects (more theory than actual code)
In this episode of AI 101 I explore Finite State Machines: one of the most important AI techniques to ever be adopted in games. I explain the theory of how it works and their application in the game that defined game AI for a generation: Half-Life.
If you're interested in learning more about finite state machines here are some links to some re...
Oh look, it even discusses the ai of the game i want to replicate
Thanks
I’m making a generic class class<T>, but I need to enforce that T has == defined. How do I do that?
can you not just use .Equals?
and if that's not enough then where T : IEquatable<T> to ensure it implements IEquatable
ty
For completeness, once Unity switches to the CoreCLR, you will be able to constrain the type to IEqualityOperators<TSelf, TOther, TResult>
Which uses the static abstract members in interfaces features, essentially allowing you to force a class to implement a static interface member
I finally solved it
The bar was there the whole time - somewhat functional too, but for some reason, transform/position was acting weird, making the bar somewhere far off-screen. I only finally saw it when I was lowkey bashing my mouse and zoomed far out only to find the damn bar instantiating in a weird place.
I changed out the "prefab transform" portion of the tutorial and it finally started functioning from there ;-; god dang a day gone over smt so stupid.
Ohmigosh, fill amount 🫥 how do I do that? That sounds way better than scale. I've been wanting to give the bar a proper asset but am stuck with flat colours cuz all I've found uses "scale" which squishes/stretches art works. Will fill amount be able to help w that?
Imma....hella take note of that from now on..
yes
you're probably better off using Unity Learn
You need an Image component, assign a valid Sprite to it, set the Sprite Mode to Filled, and tweak the fillAmount property from the code
If the bar is a solid color, a 1x1px white image will do the trick, you can change the color in the Image component
Will this work for game object? or is this for UI element?
ui, image is ui
Objects with the Image component
you can use gameobject with sprite renderer to achieve health bar but slight difficult (not much, just tune the scale and position)
Oh yeah, image is only for UI
I followed crazy monkey's cuz i specifcally needed the bar to be a game object
In that context, is there any better way to create a health bar from just game objects?
UI is made of GameObjects
I need some help. Iam making a tower defense game in 3d and i have 2 towers with an example height of 1.5 and 3. I have some cubes with a given layer to place the towers at. Now i want the towers no matter of their height to be placed on top of the cube with its button exactly on top. So basicly the 1.5 high tower being .75 above the cube and the 3 high one 1.5 above. I hope my problem is understandable heres my code iam changing the system rn so some parts are confusing. https://paste.ofcode.org/3azFEDEqDX5zHY6FUT2d6vn
Sorry, I meant without using UI Canvas
Maybe instead of saying what you don't want it to be, say what you do want it to be
explain the effect you want
Health Bar that doesn't use UICanvas
why do you have a limitation of it not using a canvas?
what are you trying to do with it
I'm attaching the "patience bar" to a customer prefab.
you know you can use world space or screen space - camera canvases for this?
I know pretty much ntg
I'm currently doing it this way cuz the bubble will automatically disappear w the customer when they "leave"
you can do that just fine with a world space canvas
I just don't know how tbh. My first version was using a canvas, couldn't wrap my head around it so I switched to this
I'm telling you the canvas is the better / easier way
what part are you confused about doing?
Make a world space canvas
put your image etc on it
make it a child of the player
My customer characters are prefabs, when I put the canvas into the prefab, everything about the bar stopped working
so debug that issue
there's no reason it can't be part of the prefab
The more I edited the script, the weirder it got - specifcally "2D instance null" or smt that messes w the gameplay itself. - even though the script I'm editing has ntg to do w that portion of the game
sounds like basic scripting errors
I spent a whole day trying to
Maybe I'll try again next time, but not now
That's my recommendation for the best/easiest way to do this
If you don't want to try it, that's fine
It is to me, never touched scripting - never touched unity
right so
some other solution that is even worse is going to be even harder for you
maybe you are jumping too far ahead, and should focus on the basics for now
What I have is kinda working
was just asking if there was a better way for future reference
it sounds like you haven't yet mastered the basics of working with prefabs, working with script references etc.
It's not like I can change it now, my stuff's due monday
you should focus on that
Defiitely
once you master the basics, this stuff will become easy
I can barely understand C#
Hello, I need help because I am making like a musician simulator and you buy beats in one scene and make the song in another scene and I want the scenes to transfer to the other scene and that you can only select the bought beats
I hope so ;-;
relateble
it's hard rn but winging it
Hi brethren ;-; suffer w me
;-;
you need some sort of storing/data base system
Either implement saving and loading between scenes or don't let the managed data be destroyed
and how do me do that?
ideally through a file saved
or like Dalphat mention, keep it in memory and dont destroy objects from prev scene
you could potentially get fancy and use something like SQLite to make a small db file
Equals was a good call, praetor. ty
void FixedUpdate()
{
Vector2 inputDirection = inputValue.normalized;
smoothedInput = Vector2.SmoothDamp(smoothedInput, inputDirection, ref smoothedInputVelocity, 0.1f);
velocityX = Mathf.Clamp(velocityX + inputDirection.x * basePlayerSpeed / 6, -(basePlayerSpeed + speedLimitAddition.x), basePlayerSpeed + speedLimitAddition.x);
velocityY = Mathf.Clamp(velocityY + inputDirection.y * basePlayerSpeed / 6, -(basePlayerSpeed + speedLimitAddition.y), basePlayerSpeed + speedLimitAddition.y);
velocityX -= velocityX * 0.1f;
velocityY -= velocityY * 0.1f;
speedLimitAddition *= speedLimitAdditionDecay;
rb.velocity = new Vector2(velocityX, velocityY);
}
so i have this code for my movement, it is quite messy but it serves its purpose and has the functionality i need, there's only 1 problem, going diagonally is faster
i have no clue how to solve it in this instance, anyone got ideas?
I'm currently getting a type mismatch when I try dropping my player into the GameObject spot for a script. In the script it is set to be a GameObject, so I'm unsure why it is throwing this error
public Rigidbody bulletRB;
private void Start()
{
playerRB = GetComponent<GameObject>();
bulletRB = GetComponent<Rigidbody>();
bulletRB.AddForce(playerRB.GetComponent<Rigidbody>().velocity.normalized * 100, ForceMode.Impulse);
}```
is this a prefab?
or did you switch types for playerRB in the script at some point?
The player is a prefab
use gameObject instead of trying to do getcomponent for it
uhh what about this object ?
screenshot inspector for this script
this also makes no sense
playerRB = GetComponent<GameObject>();
bulletRB = GetComponent<Rigidbody>();```
That is the screenshot from the inspector for the script.
its cropped. show the full object in context
Hey, is there any way to add a tile to a tile palette through script? All I could find was setting a tile in a tilemap
probably an editor script
Which object? The object the script is attached to or the Player Object?
well that doesn't really help
the object we've beeen talking about this whole time
Thank you
no the object this script is on
google is a wonderful tool
this is also a prefab yes?
Yes
I really don't know how y'all find everything, I did try googling it and found nothing
so you're trying to reference a Player in the scene
not gonna happen
really difficult. Unity Tile Palette API
wait, Player is a GameObject and a Prefab, this is the gameobject
So then how would I get the rigidbody from the player in the scene to use his momentum for projectile that's being fired?
who instantiate the bullet ?
The player
Thanks
Well I guess it's more of the gun instantiates the bullet, but the gun is a prefab that is attached to the player. Still probably works the same though?
yes as long as it has that reference, it can pass it through method paramater when instantiating bullet
This is weird, Unity showing inaccessible (private) serializefields from the parent class in subclasses in the inspector, and complaining that I'm not setting these unable-to-be-set fields.
Assuming I just remove the serializefield attributes and set the components in Awake ? anyone run into this before
someone know why this line makes my targets (red circles here) have such a offset here ?
targetPositions[i] = transform.TransformPoint(_legs[i].defaultPosition);
defaultPosition being the localPos of my legs
Show the code
Anyways, I'm experimenting with a new structure to better segregate client vs server functionality relating to Mirror as doing it all within a single Player class was becoming less maintainable.
I think this is more algebra than coding, but how can I detect the area under an object? Like a vehicle
I have a complex composite collider2D. I want to find all colliders in the scene (subject to a layer mask/contact filter) that would overlap with this collider if it were translated by a certain vector. What is the right way to do this?
I feel like there is just one specific physics method I need for this, but there are so many to choose from
should I use OverlapCollider? like, translate collider, call overlap collider, then translate it back?
Does anyone have any clever math trick to calculate a cone shape on a 2D grid? Like dnd's cone stuff, that is more clever than me just predefining shapes
is it viable to only use the inspector to just inspect, and use c# for everything else including adding components and prefabs? would it hurt performance if i set up the components and prefabs in awake()/code ?
Calculate what of a cone shape? What are you trying to do with this
it is not required to pass in the references via serializedfields. setting the references in awake seems more scalable in larger projects. there is no performance difference in doing this in awake vs inspector.
Use GetComponent in Awake if there is no ambiguity about where the component comes from.
Sometimes I'll do that if the field isn't already assigned
so that it "defaults" to looking for a sibling component
It's certainly something you could do. Of course itll affect performance if you have possibly 100s of components being added to objects all at once in awake, although itll just happen once.
I dont see a single benefit to doing this, other than trying to overdo some design pattern.
And itll make some references very annoying to setup
i want to do that so i don't have to manage both the ui and the code side, i think it would also lessen nullreference stuff
is using GetComponent faster than AddComponent?
two unrelated concepts
GetComponent retrieves an existing component.
I presume it's faster beacuse it isn't creating a new component.
I do it whenever I notice that I'm not making complex decisions
X always has Y, and Y is always configured in the same way
My game is grid based, using Vector2Ints to define squares on the playing field. I would like to come up with a clever way to give a function a position to start from say 2,4 and then a direction and a length and for it to return the squares that would constitute a cone shape in that direction from that position
the spatial audio system I built for one game automatically generates the AudioSource and the various audio filters
because I always did the same thing every time
I did have to add various knobs and levers to the spatial audio component to let me properly configure the audio source
don't you get confused between having to manage both ui and code? you'd get the component in the code anyway so why not do everything in code?
you make design decisions in the scene view.
For example, a boss enemy has a move that triggers when the player stands in a danger zone for too long
to each their own I suppose, but managing references in UI seems the greater lift and having to repopulate anytime a referenced name changes, versus having it just always keep the known reference upon name changes. in a large project with lots of prefabs, seems more time consuming to always be managing in inspector.
the code doesn't decide where that danger zone is
it also doesn't decide which danger zone it's using
that is configured in the inspector
They said it in a way like always doing it through script. I imagine itd be very tedious if you had 2 buttons and 2 doors and wanted to hook them up compared to just dragging it in inspector
I could add some hideously brittle Find call to locate the danger zone, sure
but that sounds awful
it would be nice if the inspector automatically added the c# code too, but maybe that would make it cluttered for some people, especially if it's code they didn't write
wot
Is this 2D? Because you could just do it based on triangle instead of cone which would be way easier
i definitely would not want to see my entire source file inserted into the inspector
that sounds very strange.
like adding collider in the ui would automatically add AddComponent in awake
oh, I see
that also sounds very odd, though
you'd be trying to auto-generate code that accomplishes the same thing as just assigning the reference
that code would only work if every instance of your component had a collider as a sibling
and it would malfunction if you had multiple colliders
and it wouldn't be sufficient if the colliders could be on another object
Yea theres really no point in that, and you would have a major unreadable mess when you have this happening on 100 objects for example
so basically you have to know when to balance it out?
yes
This might just be trying to adhere to some pattern toooo much. Using your inspector for inspecting only is kinda not smart
I've deliberately moved some stuff out of code and into the inspector
for example: boss move patterns
I wrote a reasonably elaborate system so that I can make a list of "steps" entirely in the inspector
now I can tweak behavior entirely graphically, without modifying the code
if I want to add a slight variation of an existing move sequence, I can just make a copy of the data
instead of writing an entirely new script
There is a point I guess where you could do this without really using inspector, but you would just be creating the equivalent of any web game
Once you have anything more than flappy bird, theres no point
Do you define the steps in code then just plug them in? Im kinda brainstorming how I want to code a similar thing
this reminded me a bit of someone making a game playable in the inspector
how does version control work with the inspector?
like in a team, isn't it important to document inspector/prefab changes?
you would explain that in the commit message, yes
so my game is built entirely around "entity states", which represent...states an entity can be in. Each entity can have many small state machines.
A "scheme" is a series of SchemeStep objects (it's a [SerializeReference]'d List<SchemeStep>).
The most important kind of scheme is the SchemeStateStep, which has a List<EntityState>
can you show a screenshot of those steps in the inspector if you have unity open now?
When it's entered, it tries to enter the first state in the list. It might wait for the state to complete, or it might do several in parallel
Ah you've lost me, I'll probably just hardcode most things lol
To keep track of when things are done, I pass "completion tokens" around. The token is passed from state to state until a "sink" is reached, which eats the token. Until the token has zero active states associated with it, the token is alive
I think it might actually be working
i also don't know why use serializedfield instead of public/getter and setter, maybe to adhere to patterns?
you mean [SerializeField] instead of a public field?
yes
This is a basic one. Note that each state is actually a "state reference". Each kind of state has its own configuration options, so I have to include that alongside the actual entity state
more `[SerializeReference]
Oftentimes, you need to be able to configure fields, but you don't need to let every class see them
2D! How would it be easier with a triangle?
A cone that's aligned to the 2D plane looks like a triangle
for example: I have a class whose sole job is to reset the game if you push the "R" key
[SerializeField] InputActionReference restartAction;
There's no reason to expose that field to other classes.
this looks like it would be easier to code but it's convenient if you have a ui for it
It's generally easier to code it once, yeah
It's also easier to code it a few times. You don't have to solve the entire problem of "how do I perform a series of attacks correctly?"
You just have to solve part of it each time.
I've run into lots of issues along the way. For example, the scheme needs to be aborted if something unexpected happens (e.g. the boss gets stunned)
or if the boss grabs the player, it shouldn't continue trying to attack; it should smoothly transition into another phase
Encapsulation is the relevant OOP concept to look into here. private/protected are both useful, and public really allows any class to modify the values, which is sometimes undesirable and how your game can become easily cheatable.
I would not say that public fields make it easy to cheat
Access modifiers are strictly there to help the programmer write more reliable code.
If the player is capable of writing and executing arbitrary code, they're going to be able to cheat
does plan scheme state derive from monobehavior or scriptable object?
Neither. These are all plain classes.
[SerializeReference]
public List<SchemeStep> steps;
plain classes' data can be saved in prefabs?
Indeed. You just need to make the class serializable.
Note that you won't be able to drag in a reference to your class -- it is not a UnityEngine.Object
It'll just show up in the inspector.
With [SerializeReference], you can use polymorphism. SchemeStep is an abstract class that I have several classes derived from.
Note that there is no built-in UI for [SerializeReference] fields. You need a third-party package to get them into the inspector
It lets me pick from a variety of options.
That's pretty cool, something like this is what I wanted to code as well
I think it might actually be working
that's nice, i'm still getting used to FSMs, even in c++/embedded stuff
It was a solid week of really boring slogging lol
and I'm still not completely happy with it
it does feel nice :p
My state machines are a bit weird. They have almost no rules for when you can switch states.
I'm still figuring out where, exactly, those decisions have to be made
Game design hard
It's a lot easier when you just hardcode some logic
which is absolutely where I started
You can start seeing patterns after a while.
multiplayer game design hard ++. deep into the mirror rabbit hole this week, and realizing it changes every aspect of my existing concept
Yea I jumped into multiplayer now I am abandoning the game and making a singleplayer combat game
well, webgl sucks, and websockets, bleh, this is what i've learnt this week
i should get back to work now
% git status | grep '.cs' | wc -l
19
i am halfway through rewriting way too much stuff at once

one thing that I really like about using a statically-typed language like C# is that I can just fix errors until the game compiles again
and it's startlingly likely that everything will work
i used to write web games in plain JS and it was miserable
when i watched a video on how to make multiplayer i got scared lol, you have to manually assign which variables are known and sent to the server
you have to think about who "owns" what
and how to handle disagreements about game state
I've prototyped one game and that's it
just ban anyone but the host ez
yea, this is the path i'm down in the latest experiment.
instead of my monolithic player.cs class
i'm onto player.cs + playerclient.cs + playerserver.cs to keep the various client/server stuff segregated. got the concept initially working tho
implementing rollback must be a nightmare
my build is dedicated server then all players are clients, never hosts
i haven't tried to do any kind of prediction or reconciliation yet
apparently the next mirror version will have some better stuff for prediction so looking fwd to seeing what they provide
and here i am making a ball collecting spinning cubes as my first class homework
Even something like this may end up chaotic. Separating your client/server stuff is fine but it's really a lot of work and even the ngo team has said it's not needed in like 98% of games
i don't discount it might be overkill and unsure how it scales into the full game yet. running an experimental concept as i'm 1 week new to mirror
it feels like adding network violates some programming principles
like a movement script should only do movement stuff, not multiplayer related stuff
Well you definitely will have to break some rules for networking to work properly. Most "programming principles" are just random things web dev people follow. The people who have too much time to think about architecture in the first place
the key for optimization is really reducing as much network traffic as possible and not syncing all things and hammering low ping clients. idk, still figuring out the right balance here. ultimately, my plan would be dedicated server on cloud then all remote players being clients, not hosts
i'll just say. dont make a game, then make it multiplayer after. that is a world of pain lol
Good afternoon. I am trying to implement mobile input, but Im having issues: I am using a class derived from OnScreenControl for the inputs. I wan to move the player with a joystick and move the camera whenever the player press somewhere in the screen. The problem is: when I press the joystick, the camera zone - which is supposed to be behind this button - also gets triggered and the camera also moves.
Is there a way to stop this from happening?
Use the event system for your camera control too
E.g. a big invisible UI element behind the onscreen control
With OnDrag etc
Or PointerDown
I'm using it, for the camera control. Now I need to make the joystick in front of the camera and dont press the camera button - which is the screen- when I press the joystick
now i'm imagining some game devs joining a morning meeting and then the boss says "we decided to add multiplayer" 3 years into development
then again some modders made multiplayer breath of the wild mods
https://github.com/HouraiTeahouse/Backroll this is apparently a port of GGPO/rollback netcode for unity, might make it easier/harder, but there's no documentation
there's even a ringbuffer class which i didn't know is possible/what you would use it for with c#
hey so is there a way to do this so that I dont have to explicitely pass the stride as a function argument and have the function able to find out the stride of the input data by itself?
Make an interface for your struct and have it return its own size
ooooo didnt know you could do that! time to figure out how
wait cant I do this?
int stride = System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
Whats the downside of this?
That would give you the size of Type
oh...
Have you tried it? Does it work? IDK it might
unsafe void Florp<T>() where T : unmanaged
{
int x = sizeof(T);
}
This doesn't give any compiler errors for me.
I get warned that T might be managed if I only constrain T to be struct
System.Runtime.InteropServices.Marshal.SizeOf takes an instance and gives you the size of it. I guess you could do...
System.Runtime.InteropServices.Marshal.SizeOf<T>(default);
it seems to work
oh wait, duh
System.Runtime.InteropService.Marshal.SizeOf<T>() works
The non-generic version is there so you can get the size of an object without any clue what its type is
sweet
is there any real downside or is it fine?
The sizeof operator returns a number of bytes that would be allocated by the common language runtime in managed memory. For struct types, that value includes any padding, as the preceding example demonstrates. The result of the sizeof operator might differ from the result of the Marshal.SizeOf method, which returns the size of a type in unmanaged memory.
It sounds like you need the Marshal.SizeOf method.
You want the unmanaged size.
never knew that. neat.
aint that what this is?
oooooo
oh, wait, I was mistaken. It has an overload.
It has two different versions that take a parameter
one takes object; one takes Type
So that would, indeed, work.
I saw the object one first and missed the Type one.
I switched to the SizeOf<T>()
as long as theres no major downsides or performance penalty or weird memory things im happy
guys, what is the difference between vector3[ , ] x; and vector3[ ] x;
the first is a 2 dimensional array of Vector3, the second is just a 1 dimensional array of Vector3
so why not write as vector[ ][ ] x;
because that's a totally different thing
because that's an array of arrays of Vector3. it's not quite the same thing as a 2 dimensional array
oooh, ok thanks for the help @somber nacelle
A multi-dimensional array is one huge array and must have consistent sizes in each dimension
An array of arrays is just a small array (that points to other arrays), and can have varying sizes
Isnt the term jagged array ?
yes, but it's still an array of arrays
Accroding to the docs Rigidbody.velocity should find the linear velocity of the rigidbody. However it seems to be taking the angular velocity and adding it to the object that is being instantiated
assigning to the velocity property of a rigidbody has nothing to do with its angular velocity. you need to provide more context as to what is happening to determine where your issue lies
though at a guess, i'd say the instantiated object is probably colliding with some other object (or depenetrating from another object if instantiated inside of it)
Hmm, there IS an angularVelocity
https://docs.unity3d.com/ScriptReference/Rigidbody-angularVelocity.html
But yeah, velocity is not it
{
if (Input.GetButtonDown("Fire1"))
{
GameObject firedBullet = Instantiate(bullet, muzzel.transform);
firedBullet.GetComponent<Rigidbody>().AddRelativeForce(player.GetComponent<Rigidbody>().velocity + new Vector3(0, bulletVelocity, 0), ForceMode.VelocityChange);
}
}```
Here is the code that I am referencing. When I spin the player object it seems to be taking the angular velocity of the player and adding it to the bullet. Because when I click "Fire" as the player is spinning, the bullet just falls in front of the player. However, when the player is standing still or moving the bullet fires off into the distance
you make it a child of the muzzel object. which means it's transform affects the child object's transform
sounds like the player is colliding with the bullet
but also yeah, could be colliding with the player
also you're adding the player's world space velocity to the bullet in Relative mode
meaning you're treating a world space vector as a local vector, which isn't correct
The bullet gets destroyed anytime anytime it collides with anything, and it's not being destroyed until it hits the ground or another object
IW as normalizing it, but removed it to see if it made a difference, and it didn't
normalizing it won't fix it
nor does it make any sense here at all
I thought "normalized" made it local space instead of world space
this is what I would expect here:
bulletRB.velocity = playerRb.velocity;
bulletRB.AddRelativeForce(Vector3.up * bulletVelocity, ForceMode.VelocityChange);```
you thought incorrectly
no idea where you got that idea from
normalizing a vector sets its length aka magnitude to 1
O
I don't want the bullet velocity to be equal to the player velocity. I want the player velocity to be added to the bullet velocity, so that if the player is moving to the right the bullet doesn't just go straight, but it goes straight and to the right
that's what my code does
It sets it to the player, then adds more on top. Which, of course, adds the player velocity to the bullet velocity
This still causes the samething to happen
then again i think it's due to a collision with the player
it's also not clear that you are instantiating the bullet with the correct rotation
you seem to be making it a child of the muzzle (why?)
Normally i'd expect you to simply spawn it with the muzzle's position and rotation
not as a child
Instantiate(bullet, muzzel.position, muzzel.rotation);```
is there a way to make 1 specific colliders ignore forces from another specific collider?
I still want collision callbacks, and collider A to still send force to collider B, but I want to conditionally stop B from sending force to A (And not just disabling for the whole layer)
doesn’t that also block callbacks?
yes it makes them ignore each other
what kind of callbacks are you expecting
if there's no collision, there's no OnCollisionEnter
if you want trigger callbacks, use trigger colliders
I get an error say that "GameObject doesn't contain a definition for rotation" And I'm not trying specifically create it as a child of muzzle
.transform.rotation
Your old code was specifically making it a child and nothing else
player/enemy is on moving block. Objects enter/exit reference frame using collision callbacks in a referenceFrameHandler script. Block can only be pushed by things not in its reference frame.
i need to be able to get the OnCollisionExit callback to know I’m no longer in the reference frame
I'm not really following
sounds complicated
SOunds like the reference frame stuff can be handled by separate trigger colliders possibly
Mario can push block.
Mario can ride moving block without falling off.
If Mario is riding a weirdly shaped block (like an L block), he should not be able to push the L block while riding it to propell it
make sense?
i handle with collision callbacks for multiple reasons I would rather not get into
alternatively, if I could listen to a message that a specific collider is receiving force from another specific collider, if I could potentially receive that and modify the force before it is applied, that would help me with several different problems
Does anyone have a script for a 2d.mobile game that lets you move side to side
using unity's playable examples https://docs.unity3d.com/Manual/Playables-Examples.html in my code why does playableGraph.IsDone() always false after the first time I called the Play() function?
Any tips?
void Update()
{
if (playss)
{
// Reset the graph before playing it again
playableGraph.Stop(); // Stop the graph
playableGraph.Destroy(); // Destroy the graph
// Recreate the graph and set it up
playableGraph = PlayableGraph.Create();
var playableOutput = AnimationPlayableOutput.Create(playableGraph, "Animation", GetComponent<Animator>());
mixerPlayable = AnimationMixerPlayable.Create(playableGraph, 2);
playableOutput.SetSourcePlayable(mixerPlayable);
var clipPlayable = AnimationClipPlayable.Create(playableGraph, clip);
var ctrlPlayable = AnimatorControllerPlayable.Create(playableGraph, controller);
playableGraph.Connect(clipPlayable, 0, mixerPlayable, 0);
playableGraph.Connect(ctrlPlayable, 0, mixerPlayable, 1);
// Play the Graph
playableGraph.Play();
playss = false;
}
weight = Mathf.Clamp01(weight);
mixerPlayable.SetInputWeight(0, 1.0f - weight);
mixerPlayable.SetInputWeight(1, weight);
Debug.Log(playableGraph.IsDone());
}
This got it working, thanks. But the weird thing is I had to change the .up to .right to get it to go forward lol
How would I increase an integer value variable gradually over time, not using a coroutine, and not using floating point numbers?
Without either? Why.
I dunno without using a float SOMEWHERE. I guess you could use Time.realtimeSinceStartup and casting it to an int and checking it against a preset wait time plus that realtime cached at start...
But... that still uses a float
could use DateTime.Ticks but thats a long not an int
@spring creek A. im already using an int so i don't want to change it B. Coroutines are taxing in a update loop
A) doesn't make sense at all. Casting exists. What would you even need to change?
B) what!?
lol well you already have your code so why bother changing it to do something else
@spring creek I'm using it for a slider (which can be used for floats by I don't want to, i want clean whole numbers) *a read only slider
well you use a float for just your timer then
but also i don't see why you need whole numbers for your slider
I dont need whole numbers i want whole numbers
why
@somber nacelle because I do (fixed it)
Then cast it to whole numbers....
this is an english only server, mate. but that's also a stupid reason. if you cannot come up with a legitimate reason and you just want to shoot down everyone's valid suggestions just because you want integers for literally no reason other than that you just want them, then why even bother trying to get help?
Bottom line, you're gonna need floating point somewhere, if not only for time, ticks, deltaTime, or something else related to the time passing
Just. Cast. It. Back. You only need it for the time, you can show the player whole numbers no problem
public class AlienMovement : MonoBehaviour
{
public float moveSpeed = 5.0f;
public Rigidbody2D rb;
public float maxVariability = 3f;
public float minVariability = -4.0f;
private void Start()
{
// Generate a random variability within the specified range
float variability = Random.Range(minVariability, maxVariability);
// Adjust the initial position of the alien based on the variability
Vector2 initialPosition = transform.position;
initialPosition.x += variability;
transform.position = initialPosition;
// Set the velocity based on variability
rb.velocity = new Vector2(variability, 0) * moveSpeed;
}
}
public class SpawnAliens : MonoBehaviour
{
public GameObject referenceObject;
public Quaternion spawnRotation = Quaternion.identity;
public int maxSpawnCount = 5;
public Collider2D colliderObject;
private float colliderWidth;
// Start is called before the first frame update
void Start()
{
colliderWidth = colliderObject.GetComponent<Collider2D>().bounds.size.x;
SpawnAlienSpaceship(referenceObject, spawnRotation);
}
void SpawnAlienSpaceship(GameObject alien, Quaternion rotation)
{
//Keeps track of the spawn count and the initial position
int spawnCount = 0;
Vector2 spawnPosition = referenceObject.transform.position;
//Checks if the gameObject exists
if (referenceObject != null)
{
while (spawnCount < maxSpawnCount)
{
spawnPosition.x += colliderWidth + 0.25f;
GameObject alienInstance = Instantiate(referenceObject, spawnPosition, rotation);
spawnCount++;
}
}
else
{
Debug.Log("Prefab reference is null. Please assign the Alien Spaceship prefab in the Inspector.");
}
}
}
The alien seems to only move to the right, I'm not too sure what's wrong
what are the values of min and maxVariablility in the inspector?
variability in the velocity, I want to spawn the alien with a randomized magnitude of velocity within that specific range
what are the values of those two variables in the inspector
oh 💀
I didn't see that
lmfao
there you go, they are only positive. so positive along the X axis is to the right
does this follow norms /j
configure your !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
unless you provide more context about what you mean, i'm going to assume this is going to answer your question https://docs.unity3d.com/Manual/PlatformDependentCompilation.html
{
DontDestroyOnLoad(gameObject);
#if UNITY_ANDROID || UNITY_IOS
//Debug.Log("Awaiting Services Init...");
await UnityServices.InitializeAsync();
//Debug.Log("Starting data collection...");
AnalyticsService.Instance.StartDataCollection();
//Debug.Log("GETTING THE TOKEN!...");
PushToken = await PushNotificationsService.Instance.RegisterForPushNotificationsAsync();
//Debug.Log("DID I GET THE TOKEN? " + PushToken);
if (!string.IsNullOrEmpty(PushToken))
{
OnPushTokenReceived?.Invoke(PushToken);
}
else
{
Debug.LogWarning("PushToken is null or empty...");
}
#endif
}``` I don't want this chunk of code to run in the editor while in play mode...
so wrap it in a conditional compile for UNITY_EDITOR
got it, thanks!
I see this screen but when I package it and run it on android, it doesnt work
oh and I only got android game id and not for iOS
:/
can anyone help me with it?
public class AlienMovement : MonoBehaviour
{
[SerializeField]
private float screenBorder = 30;
public float moveSpeed = 1.0f;
public Rigidbody2D rb;
public float maxVariability = 4.0f;
public float minVariability = -4.0f;
private Camera camera1;
private void Start()
{
camera1 = Camera.main;
// Generate a random variability within the specified range
float variability = Random.Range(minVariability, maxVariability);
// Set the velocity based on variability
rb.velocity = new Vector2(variability, 0) * moveSpeed;
}
private void Update()
{
reverseVelocity();
}
private void reverseVelocity()
{
Vector2 screenPosition = camera1.WorldToScreenPoint(transform.position);
if ((screenPosition.x < screenBorder) || (screenPosition.x > camera1.pixelWidth - screenBorder))
{
Debug.Log("HIT THE BORDER");
rb.velocity = new Vector2(-rb.velocity.x, 0);
}
}
}
The reverseVelocity method seems to work partially. The alien would sometimes glitch near the border of the screen. I'm not too sure why
i feel like i'm taking crazy pills, why is
playerVelocity.y = Mathf.Sqrt(jumpHeight * -3.0f * gravity);
setting playerVelocity.y to NaN?
There is no sqrt of a negative number
omg
Negate it after the sqrt
gravity is set to 9.8 not -9.8
Or that
so -3 is making it a negative number i'm being silly
thank you lol i have been running circles around that never considered negative numbers lol i was even looking at the doc for mathf 🤦♂️
maybe a visual of it "glitching" helps :/. Console shows "HIT THE BORDER" multiple times when the alien only hits it once
You should run reverseVelocity in FixedUpdate instead of Update
And use rb.position not transform.position
hello friends. i am trying to sync indices of a List of objects and a sphere array[] from the CullingGroup API. i can remove elements from the list, but i cant remove elements the same way from the array. so as elements are being added and removed at random orders in the List, the array index doesnt stay in sequence to the object index, i cant seem to wrap my head around keeping them in tandem. im trying to make it dynamically adaptable without breaking the order. any ideas would be appreciated.
idk what is culling group, is the remove operation on list (or array) is done by the culling group or yourself?
If yoy are working with culling groups I suggest you check out this free package https://github.com/mackysoft/Vision
thanks ive got this one on my tabs already but i need to dynamically update the list and array of spheres because the game is procedural gen
static usages work for me already
lets say i remove objects from the List, at slot [2], so then i have 1, 3, 4 etc. well since its a List, the order moves down to compensate. but the cullinggroups takes an array[] of spheres, so the array itself wont move down in order which means theres desync between the indexes
problem is that the order of which objects are added or removed from the list is not pre-determined and can occur in any order
ive tried other things such as dictionaries, structs etc. to no avail yet
i guess the problem stems from adding spheres to the objects incrementally, for every object initially it gets the same sphere index as the list index. but this works only in a static setting
list is array, as long as crud is done by you then you can control the array as list, idk if you manually remove something from array will affect anything of culling group
i think u can only clear an array entry by nulling it right
it wont shift down in index
when u remove an element from a list, the index is reduced by 1 all the elements above it move down
Iirc vision supports adding a object to the vis arrays when it is instantiated if it has the right component. Now if you want to do it yourself I dont think a list will cut it. You need to have essentially 3 arrays. One for your objects, the sphere array and one to track if a slot in the objects array is free or not. Naturally you want to pre-allocate all 3 arrays to be the same size and that size would be your maximum expected amount of objects
i tried 3 arrays as well but maybe i didnt nail it
guess i will start there
if anyone has any more ideas please mention me, and thanks @west lotus ❤️
#archived-code-general message
I see this screen but when I package it and run it on android, it doesnt work
oh and I only got android game id and not for iOS
:/
can anyone help me with it?
I need some help. Iam making a tower defense game in 3d and i have 2 towers with an example height of 1.5 and 3. I have some cubes with a given layer to place the towers at. Now i want the towers no matter of their height to be placed on top of the cube with its button exactly on top. So basicly the 1.5 high tower being .75 above the cube and the 3 high one 1.5 above. I hope my problem is understandable heres my code iam changing the system rn so some parts are confusing. https://paste.ofcode.org/3azFEDEqDX5zHY6FUT2d6vn
so what is the problem? you cant get the height of the box and place the tower on it?
Guys I'm working on a builder and I use triggers to detect if build placement is valid by tracking how many things we've collided with.
Issue is that when I am erasing it breaks it because the "OnTriggerExit" isn't called and I'm wondering about how I should approach deleting to resolve this?
Maybe I could attach a script to objects when I collide with them that has an "OnDestroy" event, so if I delete an object it can tell the collision handler that it's no longer blocking it
what do i do when i lost date
how can i get it back
do not cross post
what is that?
posting the same question in multiple channels
this is a code channel, not a code question
where you first posted #💻┃unity-talk
Alternative way would be to collect them to a list on the trigger object and loop through them in Update to see if they have become Unity null.
Yeh that'd be a fair way and maybe a cleaner way.. Slightly less efficient but not to a point that it should matter
Thanks, I'll consider it
Hello! I'm making a car game and I made this script to make the car move, but it starts flying out of nowhere, any solutions?
We don't help with AI-generated content
Please try to make your own code
Do Not [...]
Use unverified AI-generated responses in questions or answers.
Ok, sorry
Yo, i'm following along a tutorial and wrote this.
public class ObjectHit : MonoBehaviour
{
private void OnCollisionEnter(Collision other)
{
Debug.Log("Hit");
GetComponent<MeshRenderer>().material.color = Color.red;
}
}
The script works for them but not for me. The script is attached to what should be turning red. I feel like i'm missing something super obvious but I can't figure it out...
I did find it weird he calls GetComponent without specific object reference but ig its inherited throgh MonoBehaviour
The method doesn't get triggered at all which leaves me to think the issue lies outside the code, but as i said, its attached to the correct GameObject and it has a BoxCollider component
For OnCollisionEnter, you need both objects to have a non-trigger collider, and at least one rigidbody
And yes, you can call GetComponent like that, it's inherited from MonoBehaviour
both of those conditions are met
3D game right? Also make sure "Is Kinematic" is unchecked on the rigidbody
3D game yep.
The Player has a rigidbody. Kinematic is false, collision detection = continuous dynamic if that matters
Show the inspectors for both objects
on Collision enter must have rigidbody otherwise it wont work
Collision wont detect anything if no rigid body
You indeed need to make sure the object is moved in a way that respects the physics engine
Modifying transform.position isn't one
Its translating the transform, which im aware isnt ideal, but im trying to stay true to the tutorial and it works for him
public class Movement : MonoBehaviour
{
[Header("Values")]
[SerializeField, Tooltip("The amount of units moved per second in a given direction.")] float movementSpeed;
private Rigidbody body;
// Start is called before the first frame update
void Start()
{
body = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
Vector3 direction = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
transform.Translate(direction * movementSpeed * Time.deltaTime);
}
}
It's so not ideal that it won't work
i did AddForce first but that causes it to slowly build up over time, being very slow to gain speed and very slow to slow down once the key is released. Even setting the velocity to the vector directly had that effect
If that object was kinematic and the other object had a rigidbody it would work (though you should use MovePosition, not the Transform). Without that setup you have to use Rigidbody functions. And yes, it's not straight forward if you don't know what you're doing, as velocity, drag, momentum, all come into it.
so if the object that should turn red were kinematic it'd work?
The objects have to match in the collision matrix https://unity.huh.how/physics-messages/collision-matrix-3d
i see. cheers.
I changed movement.cs' Update definition to
void Update()
{
Vector3 direction = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
body.MovePosition(direction * movementSpeed * Time.deltaTime);
}
and now it wont move at all 
MovePosition doesn't take a movement vector
from the desciption it moves the object towards a vector. Shouldn't said vector be direction * movementSpeed * Time.deltaTime as well? since its a bit every frame
https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html
positionProvides the new position for the Rigidbody object.
Description
Moves the kinematic Rigidbody towardsposition.
oh yea adding the current position makes sense
any idea on what is this error ?
try restart editor
guys, i got this weird engine bug, the Button thing doesnt show in properties even in debug, i tried changing it many ways but still not, i tried on another script but its gone there too 😭😭😭
i restarted the engine and even my computer, i tried changing the unity editor version but still not
screenshot your console
I have a Unity Netcode for GameObjects multiplayer game and a GameManager in my scene. I want to create a function that will return a reference to a player's GameObject based on its connected client ID. My solution was to create a variable in the GameManager called latestRequestedPlayer which would get updated by the server when the GetPlayerByID() function was called, and this would then be returned to the object that called this function.
public void GetRequestedPlayerServerRpc(ulong id)
{
var playerObject = NetworkManager.Singleton.ConnectedClients[id].PlayerObject;
UpdateRequestedPlayerClientRpc(playerObject.gameObject);
}
[ClientRpc]
public void UpdateRequestedPlayerClientRpc(GameObject playerObject)
{
latestRequestedPlayer = playerObject;
}
public GameObject GetPlayerByID(ulong id)
{
GetRequestedPlayerServerRpc(id);
return latestRequestedPlayer;
}```
The problem is that you can't pass a GameObject in an RPC call so I'm wondering if anyone knows a solution or workaround to this.
non important informations here
Looks like you are grabbing Button from UnityEngine.UIElements instead of UnityEngine.UI
NO WAY, YOU ARE RIGHT
TYSM
🙇♂️
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Is possible to overwrite a property of a variable into a child class in unity?
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual
Assuming you meant override the behavior of a property.
Yup
So it's possible even with property, perfect
How does one correctly change the font of TMP in a script? I currently have the following code:
TextMeshProUGUI text = textObject.AddComponent(typeof(TextMeshProUGUI)) as TextMeshProUGUI;
text.font = Resources.Load("Assets/Fonts/Pixelated SDF") as TMP_FontAsset;
text.text = "Level " + (index+1);
But nothing seems to be happening. When looking at the font in the inspector, it is still the default font
When applied from the inspector tho, it works
Make sure Resources.Load does not return null, and that the type is correct. Casting with as returns null if the type cannot be converted
Recommend using a hard cast (TMP_FontAsset)Resources.Load(...) or the generic Resources.Load<T>(string)
Indeed it is null
Should have thought about trying that myself
Neither of these work unfortunately
So the resource wasn't found
Does the asset have to be inside the resources folder?
Make sure you have any Assets/Fonts/Pixelated SDF path under a valid Resources folder as per the docs
/**/Resources/Assets/Fonts/Pixelated SDF.*
(file with any extension under a "Resources" folder anywhere in the project)
Yeah, it works now, thanks! I just looked at an example where "Assets/blah/blah" was used and assumed it doesn't have to be inside the Resources folder
oh ok, Thanks
Hi. I need help. My input axis for horizontal is setting itself to -1 automatically, as my screenshot shows. I'm also sharing the full class script, but the only thing you need to notice is that direction should only change when I press keys, yet it sets itself to -1 and I am not pressing anything.
public class CombatLeaderInput : MonoBehaviour
{
NavMeshAgent agent;
[SerializeField] CombatStateSO state;
[SerializeField] CombatCharacterData ccd;
[SerializeField] Vector3 direction;
float velocity;
// Update is called once per frame
void Update()
{
if (state.State != CombatState.Active &&
state.State != CombatState.Submenu)
return;
HandleInput();
}
void HandleInput()
{
direction = new Vector3
(
Input.GetAxisRaw("Horizontal"),
0,
Input.GetAxisRaw("Vertical")
);
agent.velocity = direction * velocity;
}
void UpdateSpeed(int sogginessStacks)
{
velocity = ccd.Speed;
}
public void SetLeader(int index, CombatCharacterData data)
{
print("Calling set leader.");
if(ccd != null)
ccd.EffectsHandler.Sogginess.onStacksChanged.RemoveListener(UpdateSpeed);
ccd = data;
agent = data.GetComponent<NavMeshAgent>();
velocity = data.Speed;
data.EffectsHandler.Sogginess.onStacksChanged.AddListener(UpdateSpeed);
}
}
And here is the Input Manager.
By the way, I tried toggling between GetAxis and GetAxisRaw and the same thing still happens.
@stuck niche Nothing jumps out from the code to me.
Could you have a wireless keyboard turned on or any other devices plugged in?
9 times out of 10 that an issue with an input axis mysteriously going to one of its extremes with no input pressed has been some other input device (like a controller, steering wheel, etc) has been connected and either has drift or is actually being pressed somehow
I want to make the player move in the direction of the camera but it is moving in a weird manner, could anyone kindly take a look at my code and help me out please? Thanks in advance.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header("Player Movement")]
public float playerSpeed = 1.9f;
[Header("Player animator and gravity")]
public CharacterController cC;
[Header("Player jumping and velocity")]
public float turnCalmTime = 0.1f;
float turnCalmVelocity;
[Header("Player script cameras")]
public Transform playerCamera;
void playerMove()
{
float horizontal_axis = Input.GetAxisRaw("Horizontal");
float vertical_axis = Input.GetAxisRaw("Vertical");
//setting the direction of the player
Vector3 direction = new Vector3(horizontal_axis, 0f, vertical_axis).normalized;
//Normalization of a vector means scaling it to have a length (magnitude) of 1 while preserving its direction
//moving the player
if(direction.magnitude > 0.1f)
{ //this is to
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + playerCamera.eulerAngles.y; //to rotate player with the camera
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnCalmVelocity, turnCalmTime);
//(smooth player movement)
transform.rotation = Quaternion.Euler(0f, angle, 0f);
//rotate the player while moving
Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
//to rotate player with the camera
cC.Move(direction.normalized * playerSpeed * Time.deltaTime);
}
}
private void Update()
{
playerMove();
}
}
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Your atan2 is backwards
But yeah please format code better
Hey everyone, I have a question regarding how best to proceed with my inventory system. Right now I have the fundamentals of my inventory/item system in place, I can pick up and store items. However, I'm not sure what to do next. What's the best way of adding behaviors to specific items? For example, I want one type of item to act as a "gun", so it'd have variables for ammo, durability, and so on, as well as an equip function. Another type I could want in a "food" item, with saturation variables and so on. I'm not really sure how to achieve this without bloating my project with a bunch of different "types" of items. Anyone know a better way?
It was my USB controller. 😅 Thanks.
One way would be to layer your classes. Have ItemBehaviour inherit from MB. Then have GunBehaviour/FoodBehaviour inherit from ItemBehaviour. And any thing more specific that you plan on grouping from there just keep branching from those base classes.
I like to use scriptable object assets to define individual items
you use code to describe how consumbles as a whole work
and then you just put data on the individual consumable definitions to tell them how they function
This is a good place to use [SerializeReference]
You can have an abstract ConsumableEffect class with an Apply method
then derive it to make things like ConsumableHealthChangeEffect, ConsumableKillsYouInstantlyEffect, whatever
[SerializeReference] List<ConsumableEffect> will give you a list of effects
note that you'll need a third party package to get an editor UI for that list
also, huh, this supports UIToolkit!
I might switch to it...
I swapped z with x and it made it worse
So I have this unity method that gets called on fixed update
void ApplyMovement()
{
Vector3 moveDirection = transform.forward * movementInput.y + transform.right * movementInput.x;
Vector3 desiredVelocity = moveDirection * moveSpeed;
// Calculate the Y velocity separately to allow free vertical movement
Vector3 currentVelocity = movementManager.rb.velocity;
Vector3 yVelocity = new Vector3(0, currentVelocity.y, 0);
Vector3 xzVelocity = new Vector3(desiredVelocity.x, 0, desiredVelocity.z);
// Apply acceleration to the X and Z velocities
Vector3 accelerationVector = (xzVelocity - currentVelocity) * acceleration;
movementManager.rb.AddForce(accelerationVector, ForceMode.Force);
// Limit the maximum speed for X and Z axes only
Vector3 clampedVelocity = movementManager.rb.velocity;
clampedVelocity.x = Mathf.Clamp(clampedVelocity.x, -maxSpeed, maxSpeed);
clampedVelocity.z = Mathf.Clamp(clampedVelocity.z, -maxSpeed, maxSpeed);
clampedVelocity.y = yVelocity.y;
movementManager.rb.velocity = clampedVelocity;
}
The issue with this method is that whenever it gets called, it makes my player fall super slowly. Any idea why? If I remove this line
movementManager.rb.AddForce(accelerationVector, ForceMode.Force);
Then the player falls just fine, but if I keep it in there the player falls extremly slowly.
But I cant just remove that line because then my movement stops working obviously.
I have a fighting game I am creating where I am trying to give players the option to have tap jump on or off (being able to press up arrow to jump). I'm trying to use control schemes but it doesn't appear to work. I have one called Tap Jump and one called No Tap Jump, where Tap Jump has 2 additional keys for jumping. In practice, no matter which control scheme, the characters always have tap jump. How would I fix this?
Not to familiar with the new input system, but I would also try asking here #🖱️┃input-system
Thx
Np
I have a generic class with MyClass<T1> : IT3 where T1 : IT2. I want a property on interface IT3 that returns TI as an IT2. Is there a way to do this without being confusing?
I am not allowed to put a property in MyClass<T1> that returns T1, to satisfy an IT3 interface requirement for a method that returns IT2
I would need to make a totally different method in MyClass that returns an IT2
Why is GMTK's code coloured and mine isn't, my code also doesn't work like his in the tutorial
Is it because of the colour?
Because your IDE is not configured
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
surprising , GMTK are okay
VS for Mac?
Can someone help why when I press the C button it's does Set Active false the player + player canvas but doesn't set active true the car camera and exit trigger game object
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Carenter : MonoBehaviour
{
public GameObject cameravl;
public GameObject Player;
public bool puedoEntrar;
public CarController CarController;
public GameObject salirVehiculo;
public GameObject ButtonEnter;
// Start is called before the first frame update void Start()
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.C))
{
EnterVehicule();
}
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
Player = other.gameObject;
puedoEntrar = true;
ButtonEnter.SetActive(true);
}
}
private void OnTriggerExit(Collider other)
{
Player = other.gameObject;
puedoEntrar = false;
ButtonEnter.SetActive(false);
}
public void EnterVehicule()
{
if (puedoEntrar == true)
{
cameravl.SetActive(true);
CarController.enabled = true;
salirVehiculo.SetActive(true);
gameObject.SetActive(false);
}
}
}
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
If your game object is inactive your script methods will not be called
Wich game object? The one with the script I guess ?
( for information the game object with the script on isn't set inactive)
Hey guys, I'm having trouble remembering the name of a function that works to rotate an object n degrees per second towards a direction! If anyone knows it, thanks in advance!
Your code has gameObject.SetActive(false)
Well, I think you're thinking of two methods, lerp or movetoward combined with rotate
Or maybe something from DOTween?
Yeah found it, rotate towards seems to be filling the bill.
Thanks brother appreciate it though.
Ah yeah, of course! Glad you found it
hey so basically I'm making a clone of Breakout for school and I want it to be as accurate to the original as possible, so I'm trying to make it that the speed of the ball increases every 4th collision but I'm not sure how. my code --> https://gdl.space/wisihaleki.bash
it does count, it just doesn't affect the speed
if(count == count + 4) will never be true
In short, I think you’ll want use the modulo operator. Something like:
Float speedModifier = count % 4;
ah clever
I was thinking modulo check in the if statement, but this is pretty simple
Actually no. Sorry just do integer division
wait so how would I write that?
same but change the % to /
You may have to cast the int to float, but c# might just do it for you
RamblinQ’s idea would be to store the total count and divide (integer division) that count by 4. You can also have the if statement check if count is a multiple of 4 after you increase it
this is all a bit confusing for me since I'm not very experienced 😅
It should work fine without the conversion, they only want to increase the speed after every 4th collision
You can check if a number is a multiple of 4 by checking if it’s remainder is 0
int number = 8;
if(number % 4 == 0)
{
// 8 has a remainder of 0 therefore it’s a multiple of 4
}```
hey yall do you guys know of a way to change the move speed variable in script? its using the unityengine.xr.interaction.toolkit
the variable isn't anywhere in the script and I can't find a way to alter it
ok wait so I keep it counting, add a speedModifier that = count / 4, and then add that check inside the if statement?
Think about it like this. You count the hit 3 times. On the 4th one you increase the speed. To figure out if it was the 4th hit you would use the % to figure out if the number was a multiple of 4
woah! thank you so much that works, I changed it to this if (collision.gameObject.tag == "YellowBrick")
{
count++;
if(count % 4 == 0)
{
speed = speed + 1f;
}
sorry the formattinfg is awful I'm not used to formatting in discord
You just need a reference to it and modify it just like any other variable https://docs.unity3d.com/Packages/com.unity.xr.interaction.toolkit@2.0/api/UnityEngine.XR.Interaction.Toolkit.ContinuousMoveProviderBase.html#UnityEngine_XR_Interaction_Toolkit_ContinuousMoveProviderBase_moveSpeed
im trying to reference it from another script
when i try to get the component for the actionbasedcontinousmoveprovider
it says that it doesn't exist
how do i reference it if i can't do that?
It looks like your ide isn’t configured, the issue is probably from not having the correct using statement
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
@low summit After configuring it, when you write the same line, it’ll auto fill in the using statement
omg
u are
such a life saver
ive been wondering
why this shit isn't highlighting errors for so long
I'm having difficulty understanding the field distance in the ColliderDistance2D returned by Collider2D.Distance()
It's a method, not a field
It is used to calculate the minimum distance between it and another collider
https://docs.unity3d.com/ScriptReference/Collider2D.Distance.html
Oh wait
I misunderstood sorry
Thought you meant the method call itself. But what I said basically describes the value.
No worries-- I'm just unsure what distance its measuring exactly
If it helps to visualize it https://github.com/nomnomab/RaycastVisualization
Ahhh okay, so when they're overlapping, the distance will be negative representing the amount of penetration?
I.e. if one object was moved by distance * the normal it would be depenetrated?
Yup https://docs.unity3d.com/ScriptReference/ColliderDistance2D-distance.html
negative indicating that they are overlapped.
Also extremely awesome resource, thank you for sharing!
Sent this in #archived-networking but not sure if it's worth asking here as well as I'm not sure how to go about the code either!
Hey! I'm trying to make a game and the gist of what I want to do.
1: Player walks around environment.
2: Player closes game.
3: Final player position is sent to a network and saved.
4: Whenever somebody opens the game objects are instantiated at all those saved positions.
Is there any free way to implement this?
don't crosspost but also , are you talking about a saving system? doesn't sound like a multiplayer thing
i can't get my player from falling thru my platform
it uses a layer based collision detection but i think im just not understanding how layers work
the platform is on the ground layer
and the player is on the player layer
i checked the collision box between ground and player
shouldnt that mean my player should collide with the platform?
why are u doing this lol
u just need colliders
you shouldnt have to mess with Layer based collisions unless you specifically want to ignore layers
we're gonna do that in the future
what's that got to do with your current issue though
You need colliders for things to collide
i do have them
show both
bro just keeps falling thru them
show both object's inspectors
why does goround have rigidbody ?
why shouldnt it
because its ground and doesn't need to move?
rigidbody = physics
ur ground is falling
Sorry!! And not quite? As player positions will be saved for everyone who runs the game not just the local player.
i was just trying to do anything to make it work tbh lol
i messed with the layers so many times
im missing something idk what tho
thats why im asking
try it now without rigidbody on platform
no bro still falls straight thru
does it fall thru without Player Controller
maybe its ur script and your grounded layer on it is set to none, thats sus too
when i remove the script it doesn't fall
sounds more like storing position onto a database
omg.
i just noticed the ground layer option.
on the script.
bro how did i miss that
lol probably not knowing what that field does
idk
is it working now?
yeah now it works but my character is bouncing up and down rly fast when its on the ground
hard to know for sure , start by sharing the !code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
okay i got it working again
but now it sinks half way into the platform and i can't move
chances are your grounding is wrong
you still didn't share script so 🤷♂️
although by deault a rigidbody wouldn't sink unless the code is forcing it though
For anyone whos used the kinematic character controller on the asset store, would you say it is better than just making a custom kinematic movement script?
Ive seen that it's not really for beginners but my movement shouldnt be extremely complicated. I'll at most have walking, sprinting, jumping, hovering, dashing
by custom kinematic you mean making one using regular collider + code or character controller ?
Just like a kinematic rigidbody and move position
if its simplified make your own, maybe take some bits from it but if you look at the asset there is A LOT going on lol
The kcc on the asset store seems to have a lot going on in it, which is good but also scary since I wont know the exact ins and outs
Yea lol
I tried using it twice but found it tooo bulky to change anything on it
what was it?
also dont send raw version next time lol
I guess I'll just try to make my own, since I really dont wanna get stuck down the line on how to make it do something like dash
theres a collision field that i didn't set for the sprite i was using
and whats the alternative to raw version loool sorry
yeah exactly what I ended up doing, just adding anything to it was more work than just writing my own
when you save you get the regular link lol
o
Hi. Could somebody kick me in the right direction to solve this issue:
There are AudioClips (ogg vorbis) packed into StreamingAssets and I need to load the clips in runtime and play instantly, but i'm constantly getting the chokes while the game's loading the clip from the bundle (oggs sized 2+ Mb create a quite visible delay that i'd like to get rid of)
what is the best practice to start playing audio by chunks, loading in the background without interrupting the game
(audio doesn't have to start exaclty the same millisecond I trigger it. it is okay if the sound will start a little bit later. most important part is that it shouldn't freeze the game)
How are you loading it now?
so far i've tried coroutines with assetbundle.LoadFromFileAsync
also tried setting up addressables with the same result
with AudioSource.Play() then
So it's not an .ogg file? You've packed it into an asset bundle?
there are hundreds or audio files, so i believe i have to pack them anyway
Alright, what import settings do you have for these files? That affects how they are loaded.
compression is chunk based, as well as i've tried uncompressed
i create a reference on startup with AssetBundle.LoadFromFile
Do you have Decompress on Load enabled?
hmm, no
i think so. the freezes i can notice on my pc are caused by files about 1.7Mb+ in size
How long are those audio files?
It's recommended to use streaming for clips that long. That's one of the import settings.
yeah, sounds reasonable. is there a reference to the corresponding article to read?
This is the documentation for the import settings
https://docs.unity3d.com/Manual/class-AudioClip.html
does anyone know something about third party analytics tools for things like the playstation or the switch?
I'm writing a Debug.Log wrapper that uses the conditional compilation attribute. How should I call it ? InternalDebug sounds wrong 😄. Namimg is the bane of my existance
Hi, not sure if this is the correct place to ask but: I have a base class called UIComponent that inherits from MonoBehaviour, and I have a class called UiContextMenu which inherits from UIComponent. What I'm trying to do is assigning a list of UI components via the inspector, and I want to assign scripts that inherit from UIComponent, but it's not letting me put inheritors into the inspector field. Is there a way to achieve this?
you're doing it correctly, so more context is needed. Are you sure whatever you're trying to put there is valid? Probably the most common issue in this case is trying to assign scene objects to an asset (prefab or SO)
I'm trying to assign the script directly, apart from that everything should be correct
the script from where?
directly from the folder
that makes no sense, as a component it MUST exist on a GO. If you're trying to drag the script file itself, it's failing because the expected type is MonoScript and would be wrong and nonsensical regardless
are you doing something with reflection? Maybe I misunderstood your original intent here because I thought that was a list of UIComponent, and maybe what you wanted is a specific type that you will later create an instance of
Nah, I just wanted to make a list with the UI Components needed for a certain "page", that will then initialize all component behaviors
then you're not looking to serialize a UIComponent instance, you want to serialize Type. This design is pretty smelly though, why wouldn't you just provide a prefab with the components configured?
I'm using UI Toolkit, so behaviors have to be programmed
well I guess u could still do that, idk that's just the way I wanted to design it
pretty sure you can obj.AddComponent(monoScript.GetClass());
(also, not following the conversation)
the GetClass is the key here
Hey, Unity Economy QQ-->Anyone knows how to access "InstanceItemId" in a PlayersInventoryItem via code ??.
I can access the "PlayersInventoryItemId" easily but the "InstanceItemId" throws: " 'PlayersInventoryItem' does not contain a definition for 'InstanceItemId' and no accessible extension method 'InstanceItemId'. Although the definition is there in the docs...
Post the code for PlayersInventoryItem
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
How do I use the generic type parameter in the custom property drawer?
[CustomPropertyDrawer(typeof(UUID<T>))]
public class Drawer : PropertyDrawer {
private T[] loadedValues;
}
Seemingly I can't put T in the brackets
Hey Unity Economy QQ Anyone knows how to
You probably cant. https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/reflection-and-attributes/generics-and-attributes
[CustomAttribute(info = typeof(GenericClass3<int, T, string>))] //Error CS0416
class ClassD<T> { }
I would create a non generic UUID class with an objects array in the drawer.
I think I might be able to do this with dynamic
Do not use dynamic.
At least for use in a method
This is the plague.
In this case it's better than making inheritors for the class
How do I get the instance of the edited property with the correct type?
What do you mean ?
How does a property drawer get the actual thing it's editing instead of SerializedProperty
by using the correct field of the serialiedproperty ^
Which field is the correct one?
It depends on your property
Would anyone know if a linux server build emits an OnApplicationQuit event?
And unrelated question, is there any way of enabling a cli for headless standalone builds, i.e. taking an input through the terminal rather than keypresses

Heyo
Has any1 tried integrating Logitech G29 steering wheel with pedals into Unity editor of 2021 LTS or later? I am trying to build a driving simulator in VR, the basic car with controller and terrain are ready. I don't have the official or up to date tutorial for mapping normal keys to the steering wheel
dont crosspost
Is there a way to get a prefab's size by using its empty parent class that has no renderer component? (The children have their own scales, and I need to find the overall like box outline size of the prefab if that makes sense)
wdym prefab size?