#archived-code-general

1 messages · Page 203 of 1

acoustic sinew
#

Here is the updated line for the ground check isGrounded = Physics.Raycast(transform.position, Vector3.down, groundCheckDistance, LayerMask.GetMask("Ground"));
But for some reason it's not detecting the ground.

spring creek
#

It needs to be longer, or moved down

#

Is my guess

acoustic sinew
#

Oh, I see

hard viper
#

it depends on where he put the origin of the transform

main shuttle
hard viper
#

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

spring creek
hard viper
#

i don’t think it is less precise for edge detection. it’s just different

spring creek
#

It works though, don't get me wrong

hard viper
#

i don’t think that’s what you mean

#

it’s less specific

spring creek
#

Wrong. I meant what I said? Precision detection of a tiny area. Well, three tiny areas you can treat differently

hard viper
#

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

spring creek
spring creek
hard viper
#

i mean… it’s looking for the one point of contact under you

#

it’s getting that point’s coordinate

spring creek
#

And that point could be anywhere in a wider area if it catches the edge of the collider. Less precise

hard viper
#

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

spring creek
#

Ok, pedant as needed. Go on with your meaningless and incorrect distinction as needed. Later

hard viper
#

🤷‍♂️

#

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

acoustic sinew
#

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

hard viper
#

keydown is true the frame you press the button

spring creek
acoustic sinew
#

Yea, I want to check to make sure I'm not pressing it

hard viper
#

so that second part is usually true, except for the one frame that you press left shift

acoustic sinew
#

Wait, so it's not checking if I'm holding the keydown, only if it's pressed

hard viper
#

GetKey is true WHILE it is held down

rigid island
hard viper
#

GetKeyDown is true WHEN it is pressed

#

for one frame

acoustic sinew
#

Ahhh okay

hard viper
#

GetKeyUp is true on the one frame you let go

hard viper
#

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?

heady iris
#

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

hard viper
#

I would call GetComponentsInChildren<IResettable>(), and call ResetBehaviour on each

#

the pooling class itself won’t permanently store references to behaviours

thick terrace
acoustic sinew
#

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

spring creek
acoustic sinew
#
{
    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
spring creek
#

@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

acoustic sinew
spring creek
acoustic sinew
#

BUt what's weird, is when I release the movement keywhile grounded the player moves as if it does have momentum

spring creek
#

For input

acoustic sinew
#

Yes

spring creek
#

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

acoustic sinew
#

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

uncut vapor
#

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

pine bronze
#

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

fresh cosmos
#

actually i'll post this in editor instead

devout solstice
#

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

knotty sun
thick terrace
#

wordsArray.Any(name.Contains) if you want it even more compact

shadow laurel
#

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

leaden ice
#

it shouldn't affect gameplay

heady iris
#

Restarting the editor often sorts this kind of thing out.

shadow laurel
#

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

leaden ice
#

Yes, as mentioned, it's the inspector rendering your network variable

#

it's a bug in Unity's code

shadow laurel
#

Ahh, thanks for the explanation.

heady iris
#

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

leaden ice
#

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?

heady iris
#

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

simple egret
#

??????

#

hahaha

swift falcon
#

wrong image

simple egret
#

Indeed

heady iris
#

naturally.

leaden ice
#

I missed whatever that was 😢

simple egret
#

You need to be more concentrated lmao

swift falcon
#

it happends

swift falcon
latent latch
#

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.

gaunt garden
#

I would recommend making it an interface regardless. Inheriting from a class for this case seems overkill

hard viper
#

is it expensive at all to have an additional trigger collider that touches everything in the game all the time?

zinc parrot
#

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?

knotty sun
#

Project settings

zinc parrot
#

but that seems like a hassel for whoever downloads my tool

knotty sun
#

it's in one place

spring creek
zinc parrot
#

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

heady iris
#

You can make a custom Editor window to toggle the defines.

knotty sun
zinc parrot
#

OH!
I completely blanked on the fact that an editor script can modify the project settings... thanks!

void birch
#

Can someone tell me if this is wrong and has an error or right (this is a player wasd movement script

void birch
# void birch Can someone tell me if this is wrong and has an error or right (this is a player...

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);
}

}

rain minnow
rain minnow
void birch
#

ima see

rain minnow
# void birch 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 . . .

void birch
acoustic sinew
#

Does GetButtonUp work with the axis?

rain minnow
tawny elkBOT
rigid island
#

if its a button how can be an axis

#

so probably not

#

axis gives you float

acoustic sinew
feral rain
#

just use axis lol

rigid island
acoustic sinew
#

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

rain minnow
brisk plaza
#

Starting a Gradle Daemon, 1 incompatible Daemon could not be reused, use --status for details

rigid island
#

don't you have a vector2 for inputs? @acoustic sinew

rain minnow
acoustic sinew
rigid island
#

or something like that

#

maybe you can even swap physics materials

acoustic sinew
unique edge
#

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

tawny elkBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
rigid island
tawny elkBOT
#
Posting 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.

unique edge
rigid island
unique edge
#

ill do it in a bit

#

mb something came up that i gotta tend to

hybrid turtle
#

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

leaden ice
hybrid turtle
#

Like along xy axis xz, and yz axes

#

Sorry that was a bit unclear

cosmic rain
#

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

hybrid turtle
#

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

west lotus
#

How are you defining your third axis?

hybrid turtle
#

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

vague slate
#

Is there any way to breakpoint UnityEngine methods? Like Object.Destroy

vague tundra
#

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?

hearty sphinx
#

how do i make a cinemachine virtual cam follow a rolling ball and not rotate?

#

these are the current settings

vague tundra
#

@hearty sphinx I have no idea what a cinemachine is...
Do you have to provide a LookAt transform?

hearty sphinx
#

according to tutorials you just need a follow

vague tundra
#

Maybe worth trying quickly just incase?

hearty sphinx
#

it wouldn't work with lookat

#

same with both set to player

vague tundra
#

@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?

hearty sphinx
#

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

vague tundra
#

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

hearty sphinx
#
    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

vague tundra
#

Please describe how your camera works

hearty sphinx
#

right now i'm just setting it at a fixed position like in the picture

vague tundra
#

Then the ball will always be moving correctly relative to your camera

hearty sphinx
#

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

tawny yacht
#

Creating a age old game called BaaghChaal. Need help with coding the logic.

uncut vapor
#

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

sudden lantern
#

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?

prime sinew
#

even looking at the documentation for CharacterController will get you someplace

sudden lantern
prime sinew
sudden lantern
prime sinew
#

okay

#

you try looking up "how to move character controller to position unity"

mellow sigil
#

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

formal swift
#

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...

▶ Play video
#

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

prime sinew
#

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

simple egret
#

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

west lotus
#

Pretty much codemonkey is hot garbage

next salmon
#

.

oblique spoke
# next salmon .

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.

next salmon
#

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.

rigid island
next salmon
#

So both work fine then?

hexed pecan
#

Behaviour trees tend to be more flexible. But I can't recommend any tools. Im making my own and its a rabbit hole

rigid island
#

Behaviour trees are great, just very diffcult because unity doesn't have a built in tool

next salmon
#

Thanks for the advice yall. I'll take a deeper look into behavior trees. See how it works out.

rigid island
# next salmon Thanks for the advice yall. I'll take a deeper look into behavior trees. See how...

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...

▶ Play video
next salmon
#

Oh look, it even discusses the ai of the game i want to replicate

hard viper
#

I’m making a generic class class<T>, but I need to enforce that T has == defined. How do I do that?

leaden ice
#

and if that's not enough then where T : IEquatable<T> to ensure it implements IEquatable

hard viper
#

ty

simple egret
#

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

formal swift
#

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.

formal swift
formal swift
prime sinew
#

you're probably better off using Unity Learn

simple egret
#

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

formal swift
#

Will this work for game object? or is this for UI element?

fervent furnace
#

ui, image is ui

simple egret
#

Objects with the Image component

fervent furnace
#

you can use gameobject with sprite renderer to achieve health bar but slight difficult (not much, just tune the scale and position)

formal swift
#

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?

leaden ice
rain junco
#

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

formal swift
#

Sorry, I meant without using UI Canvas

leaden ice
#

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

formal swift
leaden ice
#

why do you have a limitation of it not using a canvas?

#

what are you trying to do with it

formal swift
#

I'm attaching the "patience bar" to a customer prefab.

leaden ice
formal swift
#

I know pretty much ntg

#

I'm currently doing it this way cuz the bubble will automatically disappear w the customer when they "leave"

leaden ice
#

you can do that just fine with a world space canvas

formal swift
leaden ice
#

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

formal swift
#

My customer characters are prefabs, when I put the canvas into the prefab, everything about the bar stopped working

leaden ice
#

there's no reason it can't be part of the prefab

formal swift
#

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

leaden ice
#

sounds like basic scripting errors

formal swift
leaden ice
#

¯_(ツ)_/¯

#

it's not a complicated setup

formal swift
#

Maybe I'll try again next time, but not now

leaden ice
#

That's my recommendation for the best/easiest way to do this

#

If you don't want to try it, that's fine

formal swift
#

It is to me, never touched scripting - never touched unity

leaden ice
#

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

formal swift
#

What I have is kinda working

#

was just asking if there was a better way for future reference

leaden ice
#

it sounds like you haven't yet mastered the basics of working with prefabs, working with script references etc.

formal swift
#

It's not like I can change it now, my stuff's due monday

leaden ice
#

you should focus on that

leaden ice
#

once you master the basics, this stuff will become easy

formal swift
#

I can barely understand C#

toxic helm
#

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

formal swift
toxic helm
formal swift
#

it's hard rn but winging it

formal swift
toxic helm
#

;-;

rigid island
dusk apex
toxic helm
rigid island
#

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

hard viper
#

Equals was a good call, praetor. ty

calm delta
#
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?

acoustic sinew
#

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);
}```
rigid island
#

or did you switch types for playerRB in the script at some point?

acoustic sinew
calm delta
rigid island
#

this also makes no sense

   playerRB = GetComponent<GameObject>();
    bulletRB = GetComponent<Rigidbody>();```
acoustic sinew
rigid island
uncut vapor
#

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

acoustic sinew
uncut vapor
rigid island
knotty sun
rigid island
#

damm

#

beat me to it was linking same thing

#

🦥

rigid island
knotty sun
#

google is a wonderful tool

acoustic sinew
rigid island
acoustic sinew
uncut vapor
rigid island
#

not gonna happen

knotty sun
#

wait, Player is a GameObject and a Prefab, this is the gameobject

acoustic sinew
acoustic sinew
rigid island
acoustic sinew
#

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?

rigid island
swift falcon
#

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

potent topaz
#

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

swift falcon
#

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.

south agate
#

I think this is more algebra than coding, but how can I detect the area under an object? Like a vehicle

hard viper
#

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?

spare dove
#

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

hearty sphinx
#

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 ?

lean sail
swift falcon
#

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.

heady iris
#

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

lean sail
#

And itll make some references very annoying to setup

hearty sphinx
#

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?

heady iris
#

two unrelated concepts

#

GetComponent retrieves an existing component.

#

I presume it's faster beacuse it isn't creating a new component.

heady iris
#

X always has Y, and Y is always configured in the same way

spare dove
heady iris
#

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

hearty sphinx
#

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?

heady iris
#

For example, a boss enemy has a move that triggers when the player stands in a danger zone for too long

swift falcon
#

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.

heady iris
#

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

lean sail
heady iris
#

I could add some hideously brittle Find call to locate the danger zone, sure

#

but that sounds awful

hearty sphinx
#

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

heady iris
#

wot

lean sail
heady iris
#

i definitely would not want to see my entire source file inserted into the inspector

#

that sounds very strange.

hearty sphinx
#

like adding collider in the ui would automatically add AddComponent in awake

heady iris
#

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

lean sail
#

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

hearty sphinx
#

so basically you have to know when to balance it out?

heady iris
#

yes

lean sail
#

This might just be trying to adhere to some pattern toooo much. Using your inspector for inspecting only is kinda not smart

heady iris
#

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

lean sail
#

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

lean sail
hearty sphinx
hearty sphinx
#

like in a team, isn't it important to document inspector/prefab changes?

heady iris
#

you would explain that in the commit message, yes

heady iris
#

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>

hearty sphinx
#

can you show a screenshot of those steps in the inspector if you have unity open now?

heady iris
#

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

lean sail
heady iris
#

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

hearty sphinx
#

i also don't know why use serializedfield instead of public/getter and setter, maybe to adhere to patterns?

heady iris
#

you mean [SerializeField] instead of a public field?

hearty sphinx
#

yes

heady iris
#

more `[SerializeReference]

heady iris
# hearty sphinx yes

Oftentimes, you need to be able to configure fields, but you don't need to let every class see them

spare dove
heady iris
heady iris
#

[SerializeField] InputActionReference restartAction;

#

There's no reason to expose that field to other classes.

hearty sphinx
heady iris
#

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

swift falcon
heady iris
#

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

hearty sphinx
heady iris
#
    [SerializeReference]
    public List<SchemeStep> steps;
hearty sphinx
#

plain classes' data can be saved in prefabs?

heady iris
#

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.

lean sail
heady iris
#

I think it might actually be working

hearty sphinx
#

that's nice, i'm still getting used to FSMs, even in c++/embedded stuff

heady iris
#

It was a solid week of really boring slogging lol

#

and I'm still not completely happy with it

hearty sphinx
#

but it must have felt nice when it worked

#

oh

heady iris
#

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.

swift falcon
#

multiplayer game design hard ++. deep into the mirror rabbit hole this week, and realizing it changes every aspect of my existing concept

heady iris
#

dies

#

I'm doing LOCAL multiplayer in this game

#

take it or leave it

lean sail
#

Yea I jumped into multiplayer now I am abandoning the game and making a singleplayer combat game

swift falcon
#

well, webgl sucks, and websockets, bleh, this is what i've learnt this week

heady iris
#

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

hearty sphinx
heady iris
#

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

hearty sphinx
#

just ban anyone but the host ez

swift falcon
#

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

hearty sphinx
#

implementing rollback must be a nightmare

swift falcon
#

my build is dedicated server then all players are clients, never hosts

heady iris
#

i haven't tried to do any kind of prediction or reconciliation yet

swift falcon
hearty sphinx
#

and here i am making a ball collecting spinning cubes as my first class homework

lean sail
swift falcon
#

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

hearty sphinx
#

it feels like adding network violates some programming principles

#

like a movement script should only do movement stuff, not multiplayer related stuff

lean sail
#

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

swift falcon
#

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

wary mortar
#

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?

leaden ice
#

E.g. a big invisible UI element behind the onscreen control

#

With OnDrag etc

#

Or PointerDown

wary mortar
#

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

hearty sphinx
#

then again some modders made multiplayer breath of the wild mods

#

there's even a ringbuffer class which i didn't know is possible/what you would use it for with c#

zinc parrot
#

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?

leaden ice
zinc parrot
#

ooooo didnt know you could do that! time to figure out how

zinc parrot
heady iris
#

That would give you the size of Type

zinc parrot
#

oh...

leaden ice
heady iris
#
    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);

zinc parrot
heady iris
#

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

zinc parrot
#

sweet
is there any real downside or is it fine?

heady iris
#

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.

zinc parrot
#

aint that what this is?

heady iris
#

That's asking it how big a Type is

#

SizeOf<T>() will do what you want.

zinc parrot
#

oooooo

heady iris
#

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.

zinc parrot
#

I switched to the SizeOf<T>()

#

as long as theres no major downsides or performance penalty or weird memory things im happy

graceful wren
#

guys, what is the difference between vector3[ , ] x; and vector3[ ] x;

somber nacelle
#

the first is a 2 dimensional array of Vector3, the second is just a 1 dimensional array of Vector3

graceful wren
#

so why not write as vector[ ][ ] x;

leaden ice
somber nacelle
#

because that's an array of arrays of Vector3. it's not quite the same thing as a 2 dimensional array

graceful wren
heady iris
#

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

steady moat
#

Isnt the term jagged array ?

somber nacelle
#

yes, but it's still an array of arrays

acoustic sinew
#

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

somber nacelle
#

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)

acoustic sinew
# somber nacelle assigning to the velocity property of a rigidbody has nothing to do with its ang...
{
    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
somber nacelle
#

you make it a child of the muzzel object. which means it's transform affects the child object's transform

leaden ice
somber nacelle
#

but also yeah, could be colliding with the player

leaden ice
#

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

acoustic sinew
#

The bullet gets destroyed anytime anytime it collides with anything, and it's not being destroyed until it hits the ground or another object

acoustic sinew
leaden ice
#

nor does it make any sense here at all

acoustic sinew
#

I thought "normalized" made it local space instead of world space

leaden ice
#

this is what I would expect here:

bulletRB.velocity = playerRb.velocity;
bulletRB.AddRelativeForce(Vector3.up * bulletVelocity, ForceMode.VelocityChange);```
leaden ice
#

no idea where you got that idea from

#

normalizing a vector sets its length aka magnitude to 1

acoustic sinew
#

O

acoustic sinew
spring creek
acoustic sinew
leaden ice
#

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);```
hard viper
#

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)

hard viper
#

doesn’t that also block callbacks?

leaden ice
#

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

acoustic sinew
leaden ice
hard viper
#

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

leaden ice
#

I'm not really following

#

sounds complicated

#

SOunds like the reference frame stuff can be handled by separate trigger colliders possibly

hard viper
#

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

swift falcon
#

Does anyone have a script for a 2d.mobile game that lets you move side to side

finite igloo
#

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());
 }
acoustic sinew
solemn wren
#

How would I increase an integer value variable gradually over time, not using a coroutine, and not using floating point numbers?

spring creek
#

But... that still uses a float

knotty sun
#

could use DateTime.Ticks but thats a long not an int

solemn wren
#

@spring creek A. im already using an int so i don't want to change it B. Coroutines are taxing in a update loop

spring creek
somber nacelle
#

lol well you already have your code so why bother changing it to do something else

solemn wren
#

@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

somber nacelle
#

well you use a float for just your timer then

#

but also i don't see why you need whole numbers for your slider

solemn wren
#

I dont need whole numbers i want whole numbers

somber nacelle
#

why

solemn wren
#

@somber nacelle because I do (fixed it)

spring creek
somber nacelle
# solemn wren <@175082927862841344> because I do (fixed it)

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?

spring creek
#

Just. Cast. It. Back. You only need it for the time, you can show the player whole numbers no problem

haughty harbor
#
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

somber nacelle
#

what are the values of min and maxVariablility in the inspector?

haughty harbor
somber nacelle
#

what are the values of those two variables in the inspector

haughty harbor
#

I didn't see that

#

lmfao

somber nacelle
#

there you go, they are only positive. so positive along the X axis is to the right

haughty harbor
#

I didn't think about checking the inspector

#

💀

#

thank you

rancid comet
#

does this follow norms /j

somber nacelle
tawny elkBOT
#
💡 IDE Configuration

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.

granite chasm
#

How does one not run some code if in the editor play mode?

#

Thanks btw

somber nacelle
granite chasm
# somber nacelle unless you provide more context about what you mean, i'm going to assume this is...
    {
        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...
somber nacelle
granite chasm
ruby valve
#

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?

haughty harbor
#
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

patent hound
#

i feel like i'm taking crazy pills, why is
playerVelocity.y = Mathf.Sqrt(jumpHeight * -3.0f * gravity);
setting playerVelocity.y to NaN?

quartz folio
#

There is no sqrt of a negative number

patent hound
#

omg

quartz folio
#

Negate it after the sqrt

patent hound
#

gravity is set to 9.8 not -9.8

quartz folio
#

Or that

patent hound
#

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 🤦‍♂️

haughty harbor
leaden ice
dense cypress
#

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.

fervent furnace
#

idk what is culling group, is the remove operation on list (or array) is done by the culling group or yourself?

west lotus
dense cypress
#

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

fervent furnace
#

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

dense cypress
#

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

west lotus
# dense cypress thanks ive got this one on my tabs already but i need to dynamically update the ...

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

dense cypress
#

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 ❤️

ruby valve
#

#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?

rain junco
#

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

fervent furnace
#

so what is the problem? you cant get the height of the box and place the tower on it?

swift falcon
#

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

prisma junco
#

what do i do when i lost date
how can i get it back

knotty sun
prisma junco
#

what is that?

knotty sun
#

posting the same question in multiple channels

prisma junco
#

oh

#

ok

#

but i really need help

#

can u plssss help me

knotty sun
#

this is a code channel, not a code question

prisma junco
#

what?

#

so where do i go?

knotty sun
oblique spoke
swift falcon
#

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

crude creek
#

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?

simple egret
#

We don't help with AI-generated content

#

Please try to make your own code

short osprey
#

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

simple egret
#

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

short osprey
simple egret
#

3D game right? Also make sure "Is Kinematic" is unchecked on the rigidbody

short osprey
#

3D game yep.

The Player has a rigidbody. Kinematic is false, collision detection = continuous dynamic if that matters

quartz folio
#

Show the inspectors for both objects

short osprey
quartz folio
#

How does "Movement" work?

#

Is it applying forces to the rigidbody?

swift falcon
#

Collision wont detect anything if no rigid body

simple egret
#

You indeed need to make sure the object is moved in a way that respects the physics engine

#

Modifying transform.position isn't one

short osprey
#
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);
    }
}
quartz folio
#

It's so not ideal that it won't work

short osprey
# quartz folio 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

quartz folio
#

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.

short osprey
#

so if the object that should turn red were kinematic it'd work?

quartz folio
short osprey
#

i see. cheers.

short osprey
quartz folio
#

MovePosition doesn't take a movement vector

short osprey
#

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

quartz folio
short osprey
#

oh yea adding the current position makes sense

potent topaz
#

any idea on what is this error ?

fervent furnace
#

try restart editor

verbal basin
#

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

knotty sun
#

screenshot your console

halcyon arrow
#

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.
verbal basin
#

non important informations here

verbal basin
oblique spoke
verbal basin
#

TYSM

#

🙇‍♂️

dusk apex
#

Thankfully the non important information was shown

#

How to post !code next time

tawny elkBOT
#
Posting 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.

verbal basin
lost carbon
#

Is possible to overwrite a property of a variable into a child class in unity?

lost carbon
#

So it's possible even with property, perfect

rocky helm
#

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

simple egret
#

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)

rocky helm
#

Should have thought about trying that myself

rocky helm
simple egret
#

So the resource wasn't found

rocky helm
#

Does the asset have to be inside the resources folder?

simple egret
#

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)

rocky helm
stuck niche
#

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.

spring creek
#

@stuck niche Nothing jumps out from the code to me.

Could you have a wireless keyboard turned on or any other devices plugged in?

somber nacelle
#

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

obsidian bridge
#

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();
}

}

somber nacelle
#

!code

tawny elkBOT
#
Posting 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.

leaden ice
#

But yeah please format code better

idle flax
#

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?

stuck niche
verbal grail
heady iris
#

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...

obsidian bridge
cold willow
#

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.

high condor
#

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?

cold willow
high condor
#

Thx

cold willow
#

Np

hard viper
#

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

torn zephyr
#

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?

knotty sun
#

Because your IDE is not configured
!ide

tawny elkBOT
#
💡 IDE Configuration

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.

mellow sigil
#

what a terrible tutorial

#

based on the screenshot

rigid island
#

surprising , GMTK are okay

leaden solstice
#

VS for Mac?

upbeat gull
#

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);
    }
}

}

leaden solstice
#

!code

tawny elkBOT
#
Posting 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.

leaden solstice
upbeat gull
#

( for information the game object with the script on isn't set inactive)

idle crow
#

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!

leaden solstice
spring creek
#

Or maybe something from DOTween?

idle crow
spring creek
dense swift
#

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

buoyant crane
broken nest
#

In short, I think you’ll want use the modulo operator. Something like:
Float speedModifier = count % 4;

buoyant crane
#

ah clever

#

I was thinking modulo check in the if statement, but this is pretty simple

broken nest
#

Actually no. Sorry just do integer division

dense swift
#

wait so how would I write that?

broken nest
#

same but change the % to /

#

You may have to cast the int to float, but c# might just do it for you

buoyant crane
# dense swift wait so how would I write that?

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

dense swift
#

this is all a bit confusing for me since I'm not very experienced 😅

buoyant crane
buoyant crane
low summit
#

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

dense swift
buoyant crane
dense swift
#

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

low summit
#

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?

buoyant crane
# low summit

It looks like your ide isn’t configured, the issue is probably from not having the correct using statement

#

!vs

tawny elkBOT
#
Visual Studio guide

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)

buoyant crane
#

@low summit After configuring it, when you write the same line, it’ll auto fill in the using statement

low summit
#

omg

#

u are

#

such a life saver

#

ive been wondering

#

why this shit isn't highlighting errors for so long

devout harness
#

I'm having difficulty understanding the field distance in the ColliderDistance2D returned by Collider2D.Distance()

spring creek
#

Oh wait

#

I misunderstood sorry

Thought you meant the method call itself. But what I said basically describes the value.

devout harness
#

No worries-- I'm just unsure what distance its measuring exactly

buoyant crane
devout harness
#

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?

devout harness
#

Also extremely awesome resource, thank you for sharing!

torn eagle
#

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?

rigid island
low summit
#

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?

rigid island
#

u just need colliders

low summit
#

its a project for a club

#

this is the script they wanted to use

rigid island
#

you shouldnt have to mess with Layer based collisions unless you specifically want to ignore layers

low summit
#

we're gonna do that in the future

rigid island
#

what's that got to do with your current issue though

#

You need colliders for things to collide

low summit
#

i do have them

rigid island
#

show both

low summit
#

bro just keeps falling thru them

rigid island
#

show both object's inspectors

low summit
rigid island
#

ok entire inspector please no cropping

#

object names

low summit
#

this better?

rigid island
low summit
#

why shouldnt it

rigid island
#

because its ground and doesn't need to move?

#

rigidbody = physics

#

ur ground is falling

torn eagle
low summit
#

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

rigid island
low summit
#

no bro still falls straight thru

rigid island
#

maybe its ur script and your grounded layer on it is set to none, thats sus too

low summit
#

when i remove the script it doesn't fall

rigid island
low summit
#

omg.

#

i just noticed the ground layer option.

#

on the script.

#

bro how did i miss that

rigid island
#

idk

#

is it working now?

low summit
#

yeah now it works but my character is bouncing up and down rly fast when its on the ground

rigid island
#

hard to know for sure , start by sharing the !code

tawny elkBOT
#
Posting 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.

low summit
#

nvm???

#

it stopped working??

low summit
#

okay i got it working again

#

but now it sinks half way into the platform and i can't move

rigid island
#

you still didn't share script so 🤷‍♂️

#

although by deault a rigidbody wouldn't sink unless the code is forcing it though

lean sail
#

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

rigid island
low summit
lean sail
rigid island
#

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

lean sail
#

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

rigid island
#

I tried using it twice but found it tooo bulky to change anything on it

low summit
#

i got it

#

dw about the link i figured it out

rigid island
#

also dont send raw version next time lol

lean sail
#

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

low summit
#

theres a collision field that i didn't set for the sprite i was using

#

and whats the alternative to raw version loool sorry

rigid island
rigid island
low summit
#

o

glossy willow
#

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)

glossy willow
late lion
glossy willow
#

there are hundreds or audio files, so i believe i have to pack them anyway

late lion
#

Alright, what import settings do you have for these files? That affects how they are loaded.

glossy willow
#

compression is chunk based, as well as i've tried uncompressed
i create a reference on startup with AssetBundle.LoadFromFile

late lion
#

Do you have Decompress on Load enabled?

glossy willow
#

hmm, no

late lion
#

That's better.

#

And it's only the longer clips that have noticeable lag?

glossy willow
#

i think so. the freezes i can notice on my pc are caused by files about 1.7Mb+ in size

glossy willow
#

it may be up to 2-3 minutes

#

but i can't tell right now how long are they exactly

late lion
#

It's recommended to use streaming for clips that long. That's one of the import settings.

glossy willow
#

yeah, sounds reasonable. is there a reference to the corresponding article to read?

glossy willow
#

thanks. i'll go and read it now

#

i can also see Preload Audio Data <- this

tacit vine
#

does anyone know something about third party analytics tools for things like the playstation or the switch?

west lotus
#

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

main token
#

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?

mossy snow
main token
#

I'm trying to assign the script directly, apart from that everything should be correct

mossy snow
#

the script from where?

main token
#

directly from the folder

mossy snow
#

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

main token
#

Nah, I just wanted to make a list with the UI Components needed for a certain "page", that will then initialize all component behaviors

mossy snow
#

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?

main token
#

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

craggy veldt
#

(also, not following the conversation)

#

the GetClass is the key here

viscid cosmos
#

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...

knotty sun
#

!code

tawny elkBOT
#
Posting 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.

orchid bane
#

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

viscid cosmos
#

Hey Unity Economy QQ Anyone knows how to

steady moat
orchid bane
steady moat
orchid bane
#

At least for use in a method

steady moat
#

This is the plague.

orchid bane
#

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?

orchid bane
steady moat
orchid bane
steady moat
stark ginkgo
#

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

inner bluff
#

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

dreamy elm
#

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)

rigid island
#

wdym prefab size?