#💻┃code-beginner

1 messages · Page 64 of 1

summer stump
#

So, I guess yes to your question, if I understand it right

sour hound
#

i used audioclips this time

#

it worked, however it caused a different issue

#

when i was shooting (playing the audio) the audio didnt move along with my character

#

so if i were to run sideways the audio would lag behind

summer stump
#

Is the source ON the player?

sour hound
sour hound
#

not exactly sure how you mean

queen adder
#

Could somebody please help me with this jittering issue

#



    
    // Update is called once per frame
    void LateUpdate()
    {


        if (Follow_Position)
        {

            // Get target values
            Vector2 TargetPos = Ship.transform.position;


            // Get default value
            Vector3 CurrentPosition = CameraObject.transform.position;


            // Calculate target values with static offset for depth
            Vector3 FinalPosition = new Vector3(TargetPos.x, TargetPos.y, -10);


            Vector3 CamAccel = new Vector3(Rigid.velocity.x * Velocity_Mult, Rigid.velocity.y * Velocity_Mult, 0);
            if (CamAccel.magnitude >= Velocity_Dist_Cap)
            {
                CamAccel = CamAccel.normalized * Velocity_Dist_Cap;
            }

            FinalPosition += CamAccel;


            // Lerp final position
            CameraObject.transform.position = Vector3.Lerp(CurrentPosition, FinalPosition, Hardness_Position * Time.deltaTime);

     

        }

  }

#

It happens when I edit the speed and have the ship move really fast

summer stump
summer stump
summer stump
sour hound
#

oh

flat slate
#

!code

eternal falconBOT
summer stump
sour hound
#

do i just replace the PlayClipAtPoint with PlayOneShot?

summer stump
sour hound
#

signature?

pliant oyster
#

How do I set the position of an object to be edge-to-edge with another object?

timber tide
flat slate
#

I want the player to change the Position if clicking the Button

sour hound
summer stump
sour hound
#

oh alright

vernal sequoia
sour hound
vernal sequoia
#

How to make the Physics.OverlapBox exactly around the object, given that the object is not static, it can rotate around its axis. Do I have to use all 8 angles of the object to create this? Because I took Vector3 ((bounds.min.x, bounds.min.y, bounds.min.z) and Vector3 ((bounds.max.x, bounds.max.y, bounds.max.z)), but when the object rotates around its axis, it doesn't exactly do what I want.

In simple terms, the goal I want to achieve is to verify that the object on which the script hangs has an intersection with another object other than the ground and its daughter objects.

The OnCollisionEnter method doesn't work for me, so the method described above has to be called once at the time I need it.

There's a little sketch of my code.
https://hatebin.com/bwyoybswvv

Don't worry about all the unnecessary variables and the general crappiness of the code, I'm just experimenting.

Thanks in advance for any help.

queen adder
pliant oyster
#

I managed to do it with this:

transform.position = new Vector2(xPosition, otherBackground.transform.position.y - otherBackground.GetComponent<SpriteRenderer>().bounds.size.y);
```Both are the same size, so this works for now.
pliant oyster
#

No to myself

topaz gorge
flat slate
#

what is otherBackground?

summer stump
pliant oyster
# flat slate what is otherBackground?

Another gameObject. Two backgrounds that scroll down, when one gets out of the screen, the other is on screen and the OG gets tp'd to the other's edge.

flat slate
#

but i dont need that

pliant oyster
#

Yea which is why I said that I responded to myself

flat slate
#

okay

#

can you help me then please?

pliant oyster
queen adder
#

also, I changed it to use MoveTowards, I still get weird effects

summer stump
summer stump
#

Have you considered just using cinemachine?

pliant oyster
queen adder
#

It doesnt happen during normal gameplay, I just make the speed really fast to stress test my scripts

queen adder
summer stump
queen adder
#

So this is a unity limitation which I can do nothing about?

#

I move the ship using rigid body

#

with fixed update

summer stump
#

If the ship is the issue, show THAT code

gilded sinew
#

i cant install package KekSmoke

summer stump
#

As I said before, use a paste site

summer stump
gilded sinew
#

oh ty and sorry!

#

where can i track when it gets back up?

#

found sorry once again

queen adder
# summer stump transform.position = Is not rigidbody movement
private void FixedUpdate()
{


    // Limit the velocity to MaxSpeed
    if (Ship_Rigid.velocity.magnitude >= MaxSpeed)
    {
        Ship_Rigid.velocity = Ship_Rigid.velocity.normalized * MaxSpeed;
    }

    if (Mathf.Abs(Ship_Rigid.angularVelocity) >= MaxTurnSpeed)
    {
        Ship_Rigid.angularVelocity = MathF.Sign(Ship_Rigid.angularVelocity) * MaxTurnSpeed;
    }


    // Calculate and apply engine force
    float EngineForce = MovementInputRaw.y;
    if (EngineForce < 0) { EngineForce = 0; }; // Remove backwards force
    EngineForce *= Acceleration;
    EngineForce *= Time.fixedDeltaTime;
    Ship_Rigid.AddForce(Ship_Rigid.transform.up * EngineForce, ForceMode2D.Impulse);

    
    // Calculate and apply rotation torque
    float RotationForce = -MovementInputRaw.x;
    RotationForce *= TurnAcceleration;
    RotationForce *= Time.fixedDeltaTime;
    Ship_Rigid.AddTorque(RotationForce);

  


    // Calculation rotation angle
    Vector2 ShipToMouseDir = Ship_Rigid.position - Mouse_WorldPoint;
    float ResultAngle = Mathf.Atan2(ShipToMouseDir.y, ShipToMouseDir.x) * Mathf.Rad2Deg + 90;


    // Apply final rotation     
    //Ship_Rigid.rotation = Mathf.LerpAngle(Ship_Rigid.rotation, ResultAngle, TurnSpeed * Time.fixedDeltaTime);
    //PlayerShip.transform.rotation = Quaternion.Euler(0, 0, PlayerShip.transform.eulerAngles.z);


}
summer stump
#

!code

eternal falconBOT
queen adder
summer stump
#

Probably want to limit velocity AFTER adding force. Otherwise it happens in the next FixedUpdate

queen adder
modern oxide
#

Hello! I am currently trying to develop a shooter game but before I do that, I am following Code Monkey's Turn based shooter game. Non of the actual coding terms have really stuck in and I would like to know how to get better at coding

tepid cobalt
timber tide
modern oxide
#

ok

median sail
#
    void Update()
    {
        earnText.text = logic.coinEarnings.ToString() + " /sec"; //line 19
    }
``` someone know why this works at pulling the information from my other logic script, and it also works updating when i press play, however i get the error spammed :

"NullReferenceException: Object reference not set to an instance of an object.
updatePrice.Update () (at Assets/updatePrice.cs:19)"
modern oxide
summer stump
timber tide
modern oxide
#

Ok thanks!

timber tide
#

There's a mix of tutorials, and I believe it goes over raycasting and such, but it's not specifically shooter tutorials

median sail
timber tide
#

you can always apply the logic to your games though since it's not exclusive to those specific tutorials

summer stump
summer stump
queen adder
modern oxide
tepid cobalt
#

i seen a dude raycast each toe on a frog so it dynamically reacted to the plane

#

was so cool

modern oxide
#

dude

#

thats fucking cool

#

God that must have been expensive tho right?

tepid cobalt
#

Yeh pre sure he was making it to sell

#

some crazy shit though imagine doing that with an octopus or something

modern oxide
#

omg

#

My computer is begging me to not doing anything like that

median sail
summer stump
median sail
summer stump
median sail
summer stump
median sail
#

it does what i want it to do but it just gives me errors

summer stump
slender nymph
#

i'd bet there's probably another component of that type in the scene where something has not been assigned

median sail
summer stump
median sail
summer stump
#

So you have two

#

Look at Text

#

On of the objects is causing the error, the other is working

median sail
#

ah yeah youre right

#

the script was attatched to both

#

working on one, not on the other

#

thanks alot 🙏

tardy ridge
#

I know that this is the right channel but i dont know Where else to put it

#

Little help pls if i touch a key on my keyboard it goes to something. For example if i touch e it opens files. I think my Windows-key is on or something pls help turn this off

wintry quarry
#

Doesn't sound unity related at all.

#

Maybe try restarting your computer

#

and/or trying a different keyboard

tardy ridge
swift wedge
#

hey this kind of got lost, and I could use some help

my prefab doesn't update!

slender nymph
#

prefabs cannot reference in-scene objects

polar acorn
swift wedge
#

when I drag the prefab into the scene, it doesn't reference anything from the scene

#

even though that's how I had it before I turned the game object into a prefab

slender nymph
#

yes because the prefab does not have references assigned. because applying the overrides does not magically make the prefab able to reference the in-scene objects

polar acorn
swift wedge
#

thank you all!!!

sterile radish
#

hi! i'm making a dungeon generation system and i want to spawn a boss room at the bottom row. however, the random room i want to turn into a boss room isnt destroying itself making my boss room not being able to spawn

https://hatebin.com/tqtredkyjo

modest dust
#

Weirdly done

#

But if the room isn't being destroyed and the boss room doesn't spawn then it just seems like your condition in the if statement is false

#

Debug the values of roomDetection and levelgen.stopgen

sterile radish
#

okay

#

stopgen seems to work perfectly fine however roomDetection seems to be null

modest dust
#

So your overlaping circle doesn't detect anything

sterile radish
#

i think its because its attatched to my level generator and my level generator stops moving after the level is generated so my overlap circle doesnt rlly detect anything

modest dust
#

Either way, I'd just slap this logic into the Level Generation itself

sterile radish
#

okay, ill try that

modest dust
#

And generate the boss room alongside other rooms within the generation itself

#

No need to play around with physics overlapping and stuff like that

sterile radish
modest dust
#

Can't say much without looking at the code

#

But the second error is fairly straightforward, you're trying to access an element out of bounds of an array

sterile radish
#

!code

eternal falconBOT
sterile radish
modest dust
#

I just love the sight of 5 nested if statements

#

Time for some reading

sterile radish
modest dust
#

Well, since you're getting an index out of bounds of the array error then it seems like the spawns array contains less elements than you're trying to access

#

Show what exactly public Transform[] spawns; is in the inspector

sterile radish
modest dust
#

Well, yeah

#

Clearly you have 4 elements in this array

sterile radish
#

omg im actually dumb

#

i mixed up the names and the array

#

im so sorry for wasting ur time

modest dust
#

No worries

sterile radish
#

now it's doing everything perfectly except its spawning the boss room on top of an existing room but tbh i think ill just leave it like this for now

#

tysm once again!

modest dust
#

It would be probably good to save these rooms into some sort of 2D array and just swap out one of the bottom rooms (rooms[max or 0][random] - depends on your indexing) for the boss room

#

Didn't read the whole code but using physics circle overlap seems a bit weird for level generation

sterile radish
topaz gorge
summer stump
sterile radish
#

!code

topaz gorge
#

I put them all to static just now but theres something in my code causing extreme lag, but ill definitly check those out

eternal falconBOT
young smelt
#

Hey I am using SQLlite with unity for my offline database. I just made an export to test for mobile but the already tested and functional code is refusing to work there

eternal needle
young smelt
#

I think it is related to my files. I dragged this file from my unity editor folder into my project that made it work (As I was told to) on my PC. but the file name had windows attacthed to it

#

I feel like I have to somehow get a mobile version

topaz gorge
sterile radish
sharp abyss
wintry quarry
wintry quarry
sterile radish
#

im only guaranteeing that all the other rooms are connected to each other

wintry quarry
#

You need to use graph algorithms like DFS to ensure your exit is connected to the entrance

sterile radish
#

cuz right now im usinga direction algorithim to see where i should place the next room

modern oxide
#

What's the best way to do FPS movement that feels good?

unreal whale
#

No

#

Different types of fps have different way

young smelt
unreal whale
#

Like Tarkov and COD

young smelt
unreal whale
#

Perhaps you should use sqlite directly instead of relying on third-party libraries

young smelt
#

what?

#

wait that works?

#

I'll look into that. Hope solution for this comes though

crisp token
#

one part of anti - cheat is preventing people from straight up adding new code to your game right?

teal viper
crisp token
wintry quarry
#

there's generally little you can do to prevent a determined attacker from making modifications to your program on their own hardware

crisp token
#

I understand that they can prevent calls and change values through memory

wintry quarry
#

of course it's possible

#

they can do literally whatever they want if they know what they're doing - it's their hardware at all

#

assume they control all the bits in memory.

crisp token
#

what if I install a virus on their computer through my game?

#

that prevents it

wintry quarry
#

Then you'd be a bad person?

frosty hound
#

You'd get zero downloads

crisp token
#

isn't that how valorant's anti cheat works

wintry quarry
#

and your app would be blacklisted by antivirus programs and windows defender

frosty hound
#

And all that wasted effort combating your fear would be for nothing.

wintry quarry
frosty hound
#

Yes but people play Riots games. People are not going to play some hobby developer's game if it requires installing additional software.

crisp token
#

ofc, i was only joking

wintry quarry
#

you can try stuff like https://easy.ac/en-us/ but nothing is perfect, it needs to be combined with other measures

#

I wouldn't worry about it for now. You should be grateful if someone considers your game fun enough and worthwhile enough to develop cheats for

#

worry about it then

#

focus on making your game fun

crisp token
#

yeah I get it, but at the same time i'm also trying to learn and this is good practice ya know. It's higher level coding than most of the stuff i've done

#

i just have one question

crisp token
#

I guess this it would be enough to the point where if I had any players, it would take some time to develop a cheat, and at that point, I could add further measures to prevent it

#

Anti-cheat seems to be a game of cat and mouse really

eternal needle
# crisp token so like, if I achieve this in such a way where they would have to add full on fu...

which part are you asking would be difficult? for the user or for you?
There are some parts that are easy to protect against by just having everything done on the server. If we take valorant for example since it was listed above, you wouldnt be able to add any code at all which lets you shoot or move faster than you should. Technically they could try to do it client side, but server side nothing will happen. There are other things though like wall hacks, which still exist to this day, which you cannot fully prevent. You have to tell the user where everyone is at some point, so people can modify their own client to show that in a benefiting way.

crisp token
wintry quarry
#

"Difficult" is kind of a relative term. Users range from "Facebook Uncle" to "Script Kiddie" to "People Who Know What They're Doing".

That last category will likely get past almost anything you come up with

#

Assuming they care enough

crisp token
#

Lets say "script kiddie"

static cedar
#

I think would be more objective if we measure solely on complexity.

summer stump
wintry quarry
#

indeed

crisp token
#

yeah that's why I asked if its equally easy to install a cheat no matter how complex that cheat is

wintry quarry
#

Yes, no matter how complex the cheat is, it can be packaged into a program that can be sold and installed easily

#

This is what most "hackers" in online games are using

#

they buy a cheat from somewhere and install it

eternal needle
# crisp token For the user. What you said makes sense. I've never tried to hack or cheat in a ...

you're right that it is a game of cat and mouse. To properly understand how to make an anti-cheat, you need understanding of how to cheat in the first place. Although premade anti-cheat already exists so no real reason to make your own.
Developing something to cheat can be extremely easy, depends on how much you prevent against. Installing it can also be really easy, if the developer of said cheat makes it user friendly. In my experiences, people who make the real cheats do not want to share it publicly because they make these for personal benefit.
If we take the most basic example, what some call a packet client, it sends custom packets and practically has no way to be detected. The only detection would be if the server notices something is off and bans the person

#

For the people who buy it, not make it: Sometimes its as easy as pressing "install", sometimes its as hard as needing to install an IDE then compile the scripts.

crisp token
#

How can premade cheats exist if the program they are trying to get into uses different architectures?

#

I understand that you can have a premade cheat that gives access to variables and stuff, but that doesn't mean it works right?

eternal needle
#

Premade anti-cheat, like the service praetor linked above

#

not premade cheats

wintry quarry
#

Ah yeah there are premade anticheats which attempt to do things like memory validation on your program to make sure nobody has modified the program

#

among many other techniques

#

But the problem with things like this is that the anticheat itself can be attacked/modified/neutered

#

and like you said - cat and mouse

crisp token
#

Okay so that answers the second part of my question, in terms of how long it would take for someone to develop a cheat, is there any way to estimate that?

wintry quarry
#

Comes down to the skill level of the person

#

and the tools they're using

#

not really estimable. I bet nowadays AI can be used 😆

crisp token
#

Well in my brain, wouldn't it require some level of analysis / understanding of how the program is running?

wintry quarry
#

yes, but there are well known patterns. For example the Unity Engine itself doesn't change much between unity games, and if you're using a well known networking library for example. that doesn't change between games either

crisp token
#

Is it that easy to exploit a networking library made by unity?

#

or are you just saying that same networking library means similar architectures

wintry quarry
#

Sure why not - especially since many of these things are open source and easy to analyze

eternal needle
crisp token
#

Alright well I really appreciate your guy's time and patience, this isn't exactly the easiest topic for me. I think for now I'll just stick to the basics of server authority and stuff, later i'll worry about maybe finding an external anti-cheat, and tackle any futhrer problems if / when arise. That's really all I can do anyways.

wintry quarry
#

Yeah don't worry about it right now

#

It's a good problem to have in that it means your game is popular enough to warrant attacking

crisp token
eternal needle
#

Unless your game gets extremely popular, the people who know what they're doing probably wont even bother making a program to cheat. Mostly i see these done if it involves real life money

#

Its more fun to find in game bugs anyways

wintry quarry
#

yep - no audience == no buyers for cheats == no cheats

eternal needle
#

If theres a market for in game item to real life money then that'll provide incentive. Like csgo markets or underground trading of currency

amber dome
#

Why is it that in this script, the jump event causes the object to rise higher than it should? (Detail, the "speed" variable has a value of 5.00f).

verbal dome
#

Unrelated (?) but you should not be moving a rigidbody with transform.position

wintry quarry
verbal dome
#

Oh and you are adding rb.velocity.y to the position too

wintry quarry
#

Definitely not unrelated - in fact as written this code will always produce:

  • jitteriness
  • inconsistent results due to the physics-ish movement in Update
amber dome
#

Because with RigidBody the movement is different from what I'm looking for. For example, with "rigidbody.velocity" it doesn't look the way I want it to.

wintry quarry
#

basically - delete that crazy line of code

wintry quarry
#

if not, remove the Rigidbody or make it kinematic and stop setting the velocity

#

if so - stop moving via the Transform

#

pick one

amber dome
#

Then I'll use Rigid Body.

wintry quarry
#

then delete the transform.position += line

summer stump
amber dome
#

I need the rigid body, to jump

wintry quarry
summer stump
amber dome
#

how?

wintry quarry
amber dome
#

I even tried, but I couldn't, maybe because of the effect of gravity

wintry quarry
#

it's not that complicated. You just need to track the object's current velocity and apply gravity

#

gravity is very simple

#

it's basically just cs velocity += gravity * Time.deltaTime; in FixedUpdate

amber dome
#

Wow, that's stupid of me. I appreciate it.

wintry quarry
#

that being said I really think you'll have an easier time with a Rigidbody

#

especially as a beginner

wintry quarry
#

no

#

You said you didn't want to use a Rigidbody

amber dome
#

speed * gravity

#
  • Time.deltaTime?
wintry quarry
#

don't conflate different issues

#

gravity is gravity

#

you can deal with other things with other code

amber dome
#

Oh yes, now I get it

verbal dome
queen adder
#

can we make a monobehaviour instance from json?

#

like an instantiate from json

deft stirrup
#

oi alguem sabe como que eu coiso o negócio de pula

#

@wintry quarry

#

como

wintry quarry
#

English only please, also don't ping me out of the blue.

deft stirrup
#

sorry

#

To program a jump in unity, do I use rigidbody gravity?

wintry quarry
#

Gravity makes things go down generally

#

Kinda the opposite of a jump

#

But I guess falling is part of jumping

queen adder
#

i hope he dont gravity*-1 to make his character jump

#

i think the main question is how to make the char jump

#

so the answer is like AddForce or something

deft stirrup
#

oh

#

thank you

#

one question

summer stump
crisp token
#

if i call a coroutine in Start(), will the script not run Update() until Start() has finished?

wintry quarry
#

the coroutine will not affect the other normal operation of the script

deft stirrup
#

i need to use "layers"

crisp token
#

not coroutine my bad

summer stump
deft stirrup
#

in program

#

in the code*

crisp token
#

Can I pause the execution of a script until a certain event?

wintry quarry
summer stump
wintry quarry
#

If you want Update not to run - you can disable the script.

crisp token
#

Like I need this script to behave so that when it is initialized it recieves a value from the server as one of it's instance variables, which takes time

wintry quarry
#

a coroutine seems prudent

#

But it really depends on what you want to do after

crisp token
#

Essentialy this is for creating a tick system. When a player spawns in, I need it to jump to the currentTick, which it has to retrieve from the server, and I don't want it do anything until it has recieved that variable

#

So, if Start() hasn't finished running, will Update() still run?

wintry quarry
#

Nothing in the entirety of the engine will run until Start finishes running

#

Unity is single threaded

queen adder
wintry quarry
#

If you're doing network requests you'll want coroutines or some kind of async

crisp token
#

alright, i'll just add a little bit of code to Update , it wont be pretty but it should work

#

thanks

queen adder
#

cant you just have another object handling it?

#

then enable the thing when your task is done/ready?

#

no unnecesssary consistent check in Update

crisp token
queen adder
crisp token
queen adder
#

so you dont need```cs
void Update()
{
if(ready) dothings;
}

crisp token
#

using multiple objects right

#

i see what you mean now, smart

crisp token
modern oxide
#

Is 2d Vector still in the new input manager?

wintry quarry
modern oxide
#

what is it now?

summer stump
wintry quarry
#

as always

#

The particular tutorial you're following should show this I believe

#

(p.s. I hate that tutorial)

modern oxide
#

Which tutorial is it?

wintry quarry
#

The one with the action map name "onFoot" and that names its input action asset "PlayerInput"

modern oxide
#

yep

#

anyways I can't find it and now I'm confused

wintry quarry
#

it will show up when you do that

modern oxide
#

oh

#

I just needed to steal a movement system and build off of it

amber dome
#

how can I reference MeshPro UIS in external scripts?

wintry quarry
amber dome
#

when i use GameObject.Find gives error

wintry quarry
#

I assume you mean TextMeshPro components?

amber dome
wintry quarry
#

they are TMP_Text

amber dome
#

basically, I need to access a TextMeshProGUI in a script that isn't associated with that object.

wintry quarry
#

There's nothing special about it

#

you reference it like any other Unity component

#

the class name is TMP_Text or TextMeshProUGUI

amber dome
#

I understand, but the problem is when it comes to finding the object on the map, do I use GameObject.Find or TextMeshPro.Find?

wintry quarry
#

make a serialized field and drag and drop in the inspector

#

There is no such thing as TextMeshPro.Find

amber dome
#

ohhhhh

#

ok

#

i understand

wintry quarry
#

GameObject.Find only finds GameObjects, not components directly. As always

amber dome
#

[SerializeField]

#

ok, ok

#

Now it worked. I appreciate it.

sterile radish
wintry quarry
#

If you don't want to deal with graphs, don't make a game that deals primarily with something like a maze that is best represented as a Graph

#

Any other way is going to just be a more complicated less efficient bastardization of a graph

nimble sorrel
#

I have an audiosource that plays throughout the game (except when paused, at which point I use Pause() to pause it). when running in my editor it works perfectly fine. however after I build it to webGL and play it through itch, pausing repeatedly causes very weird behavior. it seems to skip ahead in the audio clip. Since it doesn't seem possible to reproduce within the editor, I'm not able to do much in the way of troubleshooting at the moment (I can make a dev build if need be, but that'll have to be later tonight).
Are there any quirks about webGL builds that might cause unexpected behavior with audio files when pausing the game?

modern oxide
#

Is there a simple movement script thats easily editable

wintry quarry
#

Sure, many

#

"easily" depends on how good you are at programming of course

queen adder
#

Not sure if this is the right channel but if anyone would show me some docs for Cg, currently trying to learn it

modern oxide
wintry quarry
summer stump
summer stump
modern oxide
#

I got it working. few questions.
1). how would I get rid of that annoying clipping?
2). how would I make the gun also follow the look up and down motions?

wintry quarry
modern oxide
summer stump
eternal falconBOT
modern oxide
wintry quarry
summer stump
# modern oxide No it is

Not from those screenshots it isn't
This is unquestionable.
The colors are all wrong.

Do you get code completion?
Do errors get underlined red?

modern oxide
summer stump
summer stump
# modern oxide to the last 2 yes

Ok surprising you get that when it isn't configured all the way.
Alright then, those are the big two, so you can probably get by as is

Someone may call it out in the future if you post screenshots
Just tell them you get code completion and error underlining

silk night
#

Hey, I have around 200 enemies in my scene that I'd like to batch render, i enabled GPU instancing on the material, do i need to look for anything else?

I had these lines running before

Renderer.material.color = Color.Lerp(Renderer.material.color, Color.white, 0.02f);
[...]
            if (value < maxHealth)
                Renderer.material.color = Color.red;
``` but even disabling that, the status still shows 0 batched objects
teal viper
silk night
#

no just normal meshes

#

with the default cylinder mesh on them

teal viper
#

Where are you checking the batches info?

silk night
#

Material of the enemy

teal viper
topaz gorge
# modern oxide I got it working. few questions. 1). how would I get rid of that annoying clippi...

You get rid of the clipping by having the arms seperate and you can render the gun and hands with a seperate camera to make it seem like its not going through walls and such, also if you want legs you can also make the legs and torso seperate so you can see the legs when you look down, you seperate the arms for adjusting them, and you can also mess with you camera clipping and for multiplayer you would use a sperate mesh for the other players view along with normally its own set of animations, also i would avoid having the head on the players mesh makes your life easier

silk night
teal viper
silk night
teal viper
#

Yeah. Statistics is unreliable. Shouldn't be looking at it.

silk night
#

wow what a mess 😄

teal viper
#

It was always fishy, but especially since they released the SRPs.
They did mention making it more reliable a few years ago, but I guess that didn't work out.🤷‍♂️

topaz gorge
teal viper
#

Maybe it is fixed in the newer editor versions idk.

silk night
#

i am on the newest 2023

#

so no

teal viper
#

Maybe the fix is not included in the beta🤷‍♂️

topaz gorge
#

is 2023 even LTS?

teal viper
#

It often lacks fixes of the lts, since they're working on a separate branch

topaz gorge
#

or should i say gonna be LTS

teal viper
#

It's not lts yet, is it

topaz gorge
#

huh?

#

XD

teal viper
#

Internet says "coming in April 2024"

topaz gorge
#

mmmmm is that right

teal viper
#

Lts's are always released one year later.

topaz gorge
#

true

teal viper
#

Oh, it's tech release that's in April. The LTS itself is in 2024 Q4.

topaz gorge
#

oh

#

rip

#

GPU Instancer or Frustum Culling

amber dome
#

Where's the problem, so I can't jump while moving the object horizontally?

silk night
#

You are first adding a force (which changes velocity), then you go ahead and override velocity

topaz gorge
wintry quarry
topaz gorge
#

That also anything to do with physics you dont multiply with any type of time

amber dome
wintry quarry
#

(also which question are you answering)

amber dome
#

GMTK is powered by Patreon - https://www.patreon.com/GameMakersToolkit

Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and then give you some goals to learn ...

▶ Play video
summer stump
topaz gorge
summer stump
topaz gorge
#

Anything physics should not and will not work when being multiplied with a time variable

wintry quarry
#

deltaTime is good practice where appropriate, this is not such a place

#

in fact best practice is not to add forces in Update in the first place, though it's forgivable with an impulse one-off

amber dome
#

wow

summer stump
amber dome
#

I'm going to remove that right away

topaz gorge
#

if you want to know the proper practice of Time.deltaTime you can watch Acerola he does a really good explanation

topaz gorge
#

Time to learn the Mathmatical Concept of Frustum Culling

verbal dome
#

Unity does that by default btw

topaz gorge
#

Yeah but its good to know

verbal dome
#

Sure =)

amber dome
#

Okay, now it's worked

#

thx

topaz gorge
# amber dome Okay, now it's worked

I lied it wasnt acerola its this guy https://www.youtube.com/watch?v=yGhfUcPjXuE

DeltaTime. This video is all about that mysterious variable that oh so many game developers seem to struggle with. How to use DeltaTime correclty? I got the answers and hope this video will help to deepen your understanding about how to make frame rate independent video games.

0:00 - Intro
0:34 - Creating The Illusion of Motion
1:11 - Simple Li...

▶ Play video
summer stump
modern oxide
#

How would I make this script work if it's on my camera

topaz gorge
amber dome
#

How do I make it so that you can collide and physically interact with an object, but make it really rigid, so that it can't be pushed by another object.

verbal dome
modern oxide
verbal dome
#

@amber dome Or just give it a collider and no rigidbody at all

wintry quarry
topaz gorge
crisp token
#

@wintry quarry @teal viper just pretend i didn't ask those questions, my brain turned off a lil bit

wintry quarry
sour terrace
#
if (belt != null)
            {
                beltInSequence.Add(belt);
                return null;
            }

does anyone know how I could be getting a NullReferenceException error at the beltInSequence.Add(belt); line when there is clearly an if statement that should prevent the line from running if belt is indeed null

#

I also checked this with a debug.log put right before the line logging the belt.gameobject, and it is indeed not a null value

gaunt ice
#

How about the list

cosmic dagger
sour terrace
wintry quarry
#

it's clearly the list itself

wintry quarry
sour terrace
#

what does a list being initialized mean?

gaunt ice
#

Log the list before you call add

wintry quarry
#

assigned to an actual object

cosmic dagger
#

do you assign it to null anywhere? is the script saved?

wintry quarry
#

Debug.Log right before use or use of a debugger is required to prove it's not null

sour terrace
#

assigning a list to null isn't the same as clearing it?

wintry quarry
#

no...

#

it's like throwing the bag in the trash

#

as opposed to clearing which would be emptying the bag

cosmic dagger
wintry quarry
#

x = null;
^ "how could x be null???"

sour terrace
#

well I didn't even know it was an issue with x to be honest

wintry quarry
#

I'm using "x" as an example

hollow axle
#

how do you access variables in a class of an object from another object? Say Ball1 collides with Ball2, I want each object to get each others Traits

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class BallScript : MonoBehaviour
{
    public class Traits
    {
        public float Speed;
        public Color Color;
        public Vector3 Scale;

        // Constructor for Traits class
        public Traits(float speed, Color color, Vector3 scale)
        {
            Speed = speed;
            Color = color;
            Scale = scale;
        }
    }
private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Wall"))
        {
            StopBall();
        }
        //StopBall();
        if (collision.gameObject.CompareTag("Ball"))
        {
            Debug.Log(this.gameObject.name + " collides with " + collision.gameObject.name);
            }
        }
    }
}
wintry quarry
#

so doing that would be step 1

#

step 2 is use GetComponent to get the BallScript component from the object you collided with

#

from there you can read any data you want

hollow axle
wintry quarry
hollow axle
#

omg I'm dumb

rapid coral
#

im building a flappy bird game but the pipes are spawning closer together than i want and I cant figure out how to increase the gap between each spawn

burnt vapor
eternal falconBOT
gaunt ice
#

assume your pipe have constant height h and spawn position y of bottom pipe is b
so the top of bottom pipe is h/2+b and you want the gap has gh height, so you just set the spawn y position of top pipe be h/2+b+gh+h/2=h+b+gh

rapid coral
burnt vapor
#

Judging by the code this is the main variable that determines the final Lowest and Highest points of the pipe, no?

fossil drum
#

Oh I thought he meant horizontal close, not vertical close. UnityChanLOL

burnt vapor
#

Also, you don't need that timer variable

burnt vapor
rapid coral
burnt vapor
#

The point of this is to avoid exposing variables more than they have to be. Currently they are public and can be modified from anywhere, even other classes. Making them private restricts modification to just this sole class. This is better in terms of readability and also because you would never (ever!) write public fields.

#

The SerializeField attribute "serializes" your fields to be visible in the Unity inspector. This allows you to modify the fields from there when you are testing various values.

#

The result is being able to adjust the height offset whilst playing the game so you can get the sweet spot.

rapid coral
#

damn thanks thats helpful, i was following online resources so thats the reason for the public variables and other small inconsistencies

burnt vapor
#

That's totally fine, just learn as you go. You're not forced to do this obviously but I thought I might aswell give the input now that the actual "problem" is fixed.

rapid coral
#

this'll help me later on for other projects also

burnt vapor
#

Also please never copy Unity's coding style because their style is a result of many years of supporting a whole different language and sticking to incredibly old conventions for backwards compatibility.

#

Just an FYI because I noticed that SerializeField wiki page already has some questionable guidelines

elder umbra
#

Hey everyone, is it possible to convert an instance of the MemoryCollection to json ? I seem to have issues converting the array, but it works on each individual element of the array.

#

This is how I save the data :

#

but in debug the json string is just equal to '{}'

burnt vapor
elder umbra
#

is it not reliable ?

burnt vapor
#

It is perfectly possible but JsonUtility is too shit to convert even the simplest objects

elder umbra
#

alright then, do you know any alternatives ?

burnt vapor
#

I suggest you download the Newtonsoft JSON, or JSON.NET Unity package and use that instead

#

The syntax to serialize with it is JsonConvert.SerializeObject

elder umbra
#

Okay, will do. Thanks !

sullen ridge
burnt vapor
#

That wont work

#

System.Text.Json targets .NET versions not supported by Unity

#

You can support it, but this requires a lot extra work when Newtonsoft is a very good and popular alternative

sullen ridge
#

Fair enough, i'll remove the link 🙂

burnt vapor
#

Nah it's fine

#

To clarify, Unity runs with the .NET Standard versions since it uses Mono, where System.Text.Json targets specifically .NET 6/7/8 rather than any .NET Standard version

teal viper
runic lotus
#

Hello! anyone please could explain to me why I cant drag this Text (TMP) ?

elder umbra
fossil drum
runic lotus
# fossil drum You sure that's a `Text Mesh Pro UGUI` and not a regular `Text Mesh Pro Text`?

AH RIGHT, thank you.. on another note... i want this: when clicked on that cube/plane (well i switched to cube now, but in the pic it was a plane), i want it to be bigger, like, idk how to explain hence why I dont know what is it called to look it up on youtube (like the thing in games, 'press to inspect' then the item kinda is in the middle of the screen and looks bigger ot you

magic pagoda
#

can anyone help me?

this code works with a regular camera but mousePos doesn't update when I move my mouse when I use cinemachine

#

fixed it! ^^

hexed terrace
#

This is really bad to do.
Find is expensive
GetComponent is expensive.
Doing these in Update() is expensive.

Do it once in Start() and use Camera.main

#

@magic pagoda ☝️

magic pagoda
#

doing it in Start caused aome issues for me

unreal whale
#

I have encountered the same problem before

magic pagoda
#

Ill keep iy in mind tho

hexed terrace
#

Figure out why and fix it, dont do what you're doing in Update() 🤦

unreal whale
#

I forgot how I solved it, maybe I didn't solve it at all.

magic pagoda
unreal whale
#

Debug MousePosition

unreal whale
hexed terrace
magic pagoda
#

Ill fix it soon probs

#

Im trying to finish a game in a week

unreal whale
#

Debug MousePosition Check if there are any changes

#

debug.log(Input.mousePosition)

magic pagoda
#

I solved it-

unreal whale
#

how solved

frozen dagger
#

im confused:/
how to get image component?

unreal whale
#

拖过去

hexed terrace
#

drag and drop

unreal whale
frozen dagger
#

i mean COMPONENT, not sprite, they are named same

#

-_-

hexed terrace
#

or if you want it done in code myImageRef = GetComponent<Image>();

hexed terrace
frozen dagger
#

:/

hexed terrace
#

This is a code channel though, so if you're not doing it via code.. shouldn't be asking in here

glacial blade
#

i need help. few months ago i created 2d platoformer and now im back andthe player seems to sometimes slow down for no reason? the spead is still the same and it is multiplies by fixeddeltatime

gaunt ice
#

delete the using MicroSoft.XXXXX namespace

#

left the UI.Image in your code

hexed terrace
frozen dagger
#

no need

#

i fixed ig

#

i asked cuz Image sprites and image component uses one name, i didnt know how to get component

hexed terrace
#

Image sprites and image component uses one name

No they don't

#

"Image sprite" is Sprite and "Image Component" is Image

frozen dagger
hexed terrace
#

Neither of those are sprites

#

See how it says "(Image)" that is the type, it wants an Image component

frozen dagger
#

wait, i need to use sprite instead of image?

hexed terrace
#

This is a sprite.

#

If you want to drag a sprite from the project window into the field, then yes, that is a sprite

frozen dagger
#

okay ill try

rapid coral
#

I asked this doubt before but i didnt frame it correctly so here we go again, In this flappy bird game, i want to increase the distance between the different spawning pipes to the right of one, not the distance between one pipe and the one below it if you get it? The code for pipe spawning is here: https://hastebin.com/share/desoqototo.csharp

#

last time i asked this doubt i framed it wrong soo

gaunt ice
#

increase the spawnrate

keen dew
#

That's determined by spawnRate

#

and increase it in the inspector, not the code

rapid coral
#

Works now thank you!

verbal dome
eternal falconBOT
burnt vapor
#

I'm guessing this is not your code?

rapid coral
#

trying to learn from another person

burnt vapor
#

I see

wooden shard
#

How is this returning a null reference exception? shouldn't it just set the bool to false if it doesn't hit anything?

languid spire
#

the code is not fine. read the docs on Resources.Load

wooden shard
#

my list with the runes clears itself on start for some reason

wintry quarry
#

but also doesn't seem like it's being "cleared". Seems like the elements are being set to null.

#

assuming that's the correct line for the error

wooden shard
#

it is, I haven't set it to clear anywhere either

languid spire
#

then you need to check what you have dragged into the List in the inspector

buoyant knot
wooden shard
#

showed it in a previous screenshot

buoyant knot
#

it is null

wintry quarry
languid spire
wintry quarry
#

this doesn't tell us anything

rich bluff
#

what is the list referencing?

#

where is the script with the list? in a prefab?

languid spire
#

bet he dragged the script from the project window

wooden shard
buoyant knot
#

you should probably set it to private and serialized

#

or public get private set

runic lotus
#

Hey! what should I give to these so that this behavior stops happening:
currently when moving the marker, it can go inside the whiteboard, i want it to stop the moment it hits the surface if that whiteboard and not be able to go further

wooden shard
wintry quarry
#

Assuming they're not mistaken about which line that error is on, it seems like somewhere they're doing something like runes[0] = null;

wintry quarry
#

but typically you'd use raycasts for this

wooden shard
#

whats the site i put the code on?

wintry quarry
#

!code

eternal falconBOT
buoyant knot
#

is Rune a monobehaviour

runic lotus
buoyant knot
#

my suspicion is that rune.transform is null

#

i would use the debugger, and inspect the state of runes

runic lotus
wooden shard
keen dew
#

the object might also be destroyed

wintry quarry
# runic lotus im using the XR toolkit

you should move a proxy object with XR and have the marker move to a position along a raycast between the camera and the proxy object where the raycast hits

#

something like that

wooden shard
buoyant knot
#

you should debug.assert rune.transform is not null

rich bluff
keen dew
#

What does the debug log print?

buoyant knot
#

seeing more of the code, i suspect rune.transform is null

wintry quarry
buoyant knot
#

I would debug.log rune, then rune.transform

buoyant knot
#

the rune or the rune.transform?

burnt vapor
#

Oh nevermind you just did

languid spire
#

so show which object you are using to fill the List

rich bluff
# wooden shard its null

answer the question, where is PlayerMovement script located, and where are the Rune objects located

runic lotus
wintry quarry
#

When i say "proxy object" I just mean an invisible empty object

burnt vapor
# wooden shard its null

So, are you assigning this list in the inspector? Did you give this list a bigger size than what it actually contains? Because the remaining slots will be null

#

So you need to either make it the right size or ignore the null values

buoyant knot
#

if you make the list in inspector, i don’t see how the rune itself can be null

wooden shard
burnt vapor
wooden shard
rich bluff
#

so all of it is in the scene from the start

buoyant knot
#

it exists

burnt vapor
#

Right, that's information I was not aware of

#

Is this rune deleted at any point?

wooden shard
#

nope

buoyant knot
burnt vapor
#

Do you happen to have a second player movement script somewhere by accident?

wintry quarry
keen dew
#

transform can never be null

rich bluff
wooden shard
buoyant knot
wintry quarry
#

I mean it must be a UnityEngine.Object since it's assigned in the inspector in the screenshot

wooden shard
languid spire
#

yes, and you still haven't shown where that comes from

buoyant knot
#

is rune a monobehaviour?

wooden shard
#

yes

buoyant knot
#

then it is possible that the instance got destroyed

#

debug.log(rune is null);

#

this checks for true null

keen dew
#

The error message would be different

#

and the log would be too

buoyant knot
#

oh true

wooden shard
#

if i assign rune during runtime in ther editor it works

keen dew
#

Turn on error pause in the console and see what's in the list when it throws the error

wooden shard
#

there's nothing in the list, it clears when the game starts

languid spire
#

which is why I keep asking what do you fill the list with?

wooden shard
#

it holds runes that i assign in the editor, rune is just a gameobject with a Rune script attached thats a child of the cube that holds the playermovement script

rich bluff
wooden shard
rich bluff
#

add something like

        private void OnDestroy()
        {
           Debug.Log("Destroyed");   
        }

to Rune

wooden shard
#

doesn't print

rich bluff
#

ok we excluded

  • duplicate PlayerMovement
  • Prefab/Scene serialization issues
  • Nothing in PlayerMovement clears the list
  • Rune is never destroyed
#

click the list variable and Find All References

wintry quarry
#

possibly another script is doing it

#

oh yeah Find All References would help here too'

wooden shard
#

should i be initializing it? doesn't work if i do or dont anyway

wintry quarry
#

we're looking for code on other scripts that might be modifying the list

wintry quarry
rich bluff
#

unity serialization doesnt allow nulls by default

rich bluff
wooden shard
wintry quarry
#

right i was looking for compile errors not runtime errors with that

#

anyway something isn't exactly adding up

#

are we totally sure you indicated the correct line for the error?

#

What's the current code look like vs the current error message? Which line number is showing?

gaunt ice
#

change it to for loop and log the index and check the element one by one
log the transform as well

#

ie log everything

rich bluff
#

press pause in editor, then play, it will pause on first frame

#

check if list is null on first frame

#

since you are dealing with coroutines, lets exclude them as well

wooden shard
#

code and error

wooden shard
wintry quarry
#

it shouldn't...

wooden shard
#

doesn't print destroyed when it isn't paused though

gaunt ice
#

how the inspector looks like right after NRE?

wooden shard
#

this is how it looks after i press start, just deletes whats in the list

rich bluff
#

go through everything and try to find some clue

#

it may be something that destroys all children of the cube, or some specific code that messes it up somehow

formal raptor
#

I want to create two prefabs using different instances of the same material, which should be reflected in editor mode for the artist to set them into the map. What is the proper way to do that without leaking, and without having to create two different material assets?

rich bluff
#

probably MaterialPropertyBlock

hexed terrace
#

hmm.. suppose you don't get the list of them in the window that way

rich bluff
#

and its slower

wooden shard
#

im just gonna make it so that the rune adds itself to the list when the game starts but thanks everyone who tried to help fix it

gaunt ice
#

dont declaring anything as public next time...

rich bluff
#

as best as you can, copy the thing to a new empty scene

#

if it works there isolated, duplicate original scene and start removing objects from it that can potentially affect it

queen saffron
#

Hey guys. I'm having an error while trying something I saw on a tutorial, can you help?

gaunt ice
#

just ask

cosmic dagger
queen saffron
#

I'm trying to use SerializeField but it prompts this

wintry quarry
#

in your code

#

(but correctly in Discord which is funny)

queen saffron
#

ok i tried the other way as well

cosmic dagger
#

what other way?

queen saffron
#

like the correct way

#

it still prompts the same stuff

cosmic dagger
#

can't tell unless you show us . . .

wintry quarry
#

anyway it kinda sounds like your IDE is not configured

cosmic dagger
#

does the tutorial have the using statement at the top of the script?

wintry quarry
#

you should set that up so you don't spend hours on silly little issues like this

queen saffron
#

ok guys it was actually misspell

#

im so ashamed i wanna quit the server

wintry quarry
queen saffron
#

yeah

wooden shard
wintry quarry
cosmic dagger
queen saffron
#

ı tried it with two different IDEs

wintry quarry
#

Sounds like it's not configured if you're not getting autocomplete

queen saffron
#

no no i just got autocomplete

rich bluff
queen saffron
#

i was typing so fast it didnt show that suggestion

#

now it did so problem solved thanks

wooden shard
rich bluff
#

do you have any plugins?

wooden shard
#

can't even try updating the unity version cause i have to use the version installed on my universities computers

rich bluff
#

third party assets/packages

#

because that "when i pause it gets destroyed" sounds like some third party code

wooden shard
rich bluff
#

work around it, but keep it in mind and keep your eyes peeled, the solution may pop up unexpectedly

oblique gale
#

I don't understand why I couldn't edit the polygon collider?

gaunt ice
#

there should be a button next to it, try restart editor

oblique gale
wintry quarry
#

You don't. Report a bug to Unity, upgrade your editor, restart the editor, etc.

rich adder
buoyant knot
ruby python
#

Bit of a random one, but is it possible to use objects as text? For example on screen score using objects instead of using text/textmeshpro ?

cosmic dagger
wintry quarry
#

so it's unclear what you're asking

ruby python
#

Sorry, I mean using 3d Models. (just thinking ideas atm), ie, instead of using text/textmeshpro to represent the number 1 for example, use a 3dmodel of a number 1

rich bluff
rich bluff
#

you can even extend TMP script and override its mesh generation methods with your own

ruby python
stiff stump
#

I have a question about gameobject brushes. is there a way to implement rule tiles with a gameobject brush?

wintry quarry
#

for every character in the string, spawn an object with a meshrenderer and the mesh corresponding to the character

ruby python
#

I shall give it a go. No doubt I'll have questions. lol.

#

Thanks 🙂

wintry quarry
#

could use prefab variants too

ruby python
#

Yeah I've got a couple of thoughts now 🙂 Thank you.

oblique gale
#

I tried doing raycast for mouseover function on a sprite. it worked. but once I used it on both sprites, they both mouse overed even though the mouse isn't there. how can I fix that?

Class A/Sprite A```C#
private SpriteRenderer objectSprite;

void Update()
{
    RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
    if (hit.collider != null)
    {
        Color color = ColorUtility.TryParseHtmlString("#D2CCF1", out color) ? color : Color.black;
        objectSprite.color = color;
    }
    else
    {
        objectSprite.color = Color.white;
    }
}

void Start()
{
    objectSprite = GetComponent<SpriteRenderer>();
}```

Class B/Sprite B```C#
private SpriteRenderer objectSprite;

void Update()
{
    RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
    if(hit.collider != null)
    {
        Color color = ColorUtility.TryParseHtmlString("#D2CCF1", out color) ? color : Color.black;
        objectSprite.color = color;
    }
    else
    {
        objectSprite.color = Color.white;
    }
}

void Start()
{
    objectSprite = GetComponent<SpriteRenderer>();
}```
wintry quarry
#

but the bug in your code is that it's only checking if your raycast hit anything rather than hit this object in particular

#

Also if you're doing a 2d raycast for the pointer like that you should be using Physics2D.GetRayIntersection(Camera.main.ScreenPointToRay(Input.mousePosition)

#

2d raycast is for rays from one point in the 2d world to another
Also why do you have two scripts that do the exact same thing?

minor cloud
#

Hey, I dont know if this is the right channel, but could it be that "Lobby" doesnt currently work?

wintry quarry
minor cloud
#

Yes its thanks I go there

oblique gale
obsidian parcel
#

Hi have a basic shader in which i wanna control the emissive map intensity withcode at runtime like 0 to 1 and 1 to 0 do any one know how to do that

wintry quarry
#

note that this is for the Standard shader, the URP shader may have a slightly different name for that property

#

you can find the name with the shader inspector as shown

green copper
#

Why does this break with .y ?

ruby python
#

iirc you can't set it directly, you haveta do it through variables.

keen dew
rich bluff
#

its explained on that page, but im pointing at it, its the essence of why you cant do it

green copper
#

So solution is this?

rich bluff
#

yes, sadly

green copper
#

That's

#

huh

#

Don't like that

rich bluff
#
        Vector2 test()
        {
            return new Vector2();
        }
        void test1()
        {
            test().x = 5;
        }
cosmic dagger
# green copper

position is an auto property of a Vector3, which is a struct. when accessing the property, it returns a copy, therefore, you cannot set any of the variables: x, y, z, for the property as they do not tie (exist) to anything . . .

rich bluff
green copper
#

Ohhhhhhkay so it's like the scope issues solved by passing by reference in c++, except in Unity the scope come from passing from game environment to script

rich bluff
#

in c# structs are copied by value by default

green copper
#

Okay I see now

#

yeah

#

still don't like that, cursed code, but at least I understand now

rich bluff
#

you can reduce it by writing it shorter

green copper
#

that actually answers a lot of annoying questions from the past few weeks

#

oh?

rich bluff
#
var tPos = transform.position;
tPos.x = 5;
transform.position = tPos;
#

you dont need to type out the type of swap vars

cosmic dagger
# green copper

by default, structs are copied. if you change any field or property of one, you have to assign the entire struct back . . .

green copper
cosmic dagger
#

extension methods come in handy when dealing with structs, namely, position from Transform . . .

green copper
#

teacher was big on readable, understandable code, with or without comments

rich bluff
#

right you can use extension methods for that

green copper
#

what's that?

plain cave
#

Hi! Question regarding transforms. Context is that I'm experienced with 3D math and graphics in general, but new to Unity. And the way transforms (we can keep it to translations) work is having me confused.

In other frameworks, including ones I've written from scratch, each model would have a transform matrix. If there's a parent relationship between models, the matrix would be multiplied with each parent to find final position in 3D space. This matrix data structure would be totally unrelated to the parent: if you have an object at an offset of (1, 2, 3) from its parent, and you reparent it, it would have the exact same offset to its new parent.

But this does not seem to be how Unity and GameObjects work. The translation of children seems to be very related to if the parent relationship was setup before or after the translation happened. I'm a bit vague here, but that's because I can't see the pattern. I've tried using both position and localPosition, but can't seem to find any logic in it.

Is there an easy explanation of how Unity transforms are supposed to work for someone used to simply having transformation matrices multiplied like I described above?

rich bluff
# green copper what's that?
    public static class TransformExt
    {
        public static void SetPosition(this Transform tr, float? x = null, float? y = null, float? z = null)
        {
            var pos = tr.position;
            if (x.HasValue)
                pos.x = x.Value;
            if (y.HasValue)
                pos.y = y.Value;
            if (z.HasValue)
                pos.z = z.Value;

          tr.position = pos;
        }
    }


        void test()
        {
            Transform tr = null;

            tr.SetPosition(y: 5);
        }
#

example of what you can do with extension methods

#

forgot to assign at the end

green copper
#

so essentially just, making a reusable function to automate the cursed bit? or is there something more I'm not seeing?

rich bluff
#

no thats it

green copper
#

Also why would it need to be static? I'm still learning when to use static and new and const and stuff like that

rich bluff
#

thats how extension methods are declared, in a static class

gaunt ice
#

unity tends to preserve the position in world space
you maybe fan of unsafe collection since you can use pointer without get/setter...

green copper
#

I see, thanks for your help

rich bluff
#

this is disabled by the optional bool parameter in most SetParent family methods

#

keepWorldPosition or something similar

#

editor tools, drag and drop have the same default behavior

#

with it set to false you get unmodified matrix

plain cave
cinder plover
#

I have a gun and a bullet. When the gun shoots the bullet, the bullet is rotated 90 to the left. I have tried rotating the bullet prefab, and changing the rotaton in code. Nothing fcking works please help

wintry quarry
#

is this a 3D object?

#

2d sprite?

cinder plover
#

Yeah

wintry quarry
#

Your 3D mesh is likely exported/imported incorrectly

#

If you put it in the scene and set tool handle rotation to local - the blue arrow should point along the bullet's forward direction

cinder plover
#

Well yeah it shoots to that direction

#

But the front of the bullet is not facing there

wintry quarry
#

that's your issue

#

you have to fix the 3D model

#

you could work around it by giving it an empty parent which faces the right way - or re-export the model from blender or wherever with the appropriate settings

cinder plover
#

What if i downloaded the model and have no experience in 3d modeling

rich adder
#

learn

wintry quarry
cosmic dagger
cinder plover
#

ill try it ig

#

ty all

#

Uh i did that and bullets are not being shot from the gun they just spawn somewhere randomly

#

no clue why

rich adder
cinder plover
rich adder
cinder plover
#

kk

rich adder
#

make sure the pivot mode in scene is visible 😛

#

currently writing something for this very issue

cinder plover
#

this is the fire point ( its moved away cuz 3d model is weird)

rich adder
cosmic dagger
#

the pivot for your bullet is completely off . . .

cinder plover
cosmic dagger
#

it should be at the base of the model . . .

cinder plover
rich adder
#

all you have to do is parent it to an empty gameobject. Move the mesh until it matches empty pivot, then parent it

wooden bay
#

Light2D only has additive and multiply I just want them the circle light to stack over the other one, and I don’t know what to do

cosmic dagger
# cinder plover And how do i do that?

as Praetor mentioned earlier, use an empty GameObject as a parent of the bullet. move the bullet until it aligns to the pivot of the empty GameObject, then parent the bullet to the empty GameObject, or just use Blender and fix the bullet's pivot . . .

verbal dome
#

Fixing the model is always preferred, extra gameobjects have overhead

rich adder
#

still not corrent

#

unless ur in World Space (dont adjust pivots in world pivot mode)

#

Blue shold be where bullet points

cinder plover
#

Ah kk

cosmic dagger
# cinder plover Like this?

much better, but not quite. the bullet should be facing the z direction (blue arrow) and the bottom should be aligned at the center axis (where all three arrows converge) . . .

cinder plover
rich adder
#

just rotate the child bullet with X rotation until points with blue

queen adder
#

do anyone know why i when i try to change a bool of animator in a private void it works, but not in a public void ?

rich adder
#

there shouldn't be any functional difference

#

you have something else wrong and misunderstanding the issue prob

queen adder
#

in the same funtion it can change a float in animator but not a bool, i don't get it

rich adder
#

🤷‍♂️ you haven't provided code we can just guesstimate

cinder plover
#

Anything else?

queen adder
#

private void Attacking()
{
if (_input.attack)
{
_animator.SetBool(_animIDAttack, true);
}
}

this works, when i change true or false

#

public void EndOfAttack()
{
_animator.SetFloat(_animIDAttackNumber, 0);
_animator.SetBool(_animIDAttack, false);
}

this doesn't works, only the setfloat works, the setbool is ignored

rich adder
#

you probably have a nother function setting it at the sametime

#

this isn't the full context of the code

#

where do you call Attacking and EndOfAttack

#

etc

queen adder
#

the animation calls it when it ends, the setbool is called nowhere else

gusty gyro
#

hello!, do you guys have suggestion or some code for this one? i want to handle slope and curves when my character moves, my character using polygon collider 2D

cinder plover
sage mirage
#

Hey, guys! If I want to save my changes in settings on my game with a button for example Save or Apply how can I do that? I mean all my settings on my game.

torn plover
#

What is the best way to handle damage?
Should the weapon subtract the health from a target?
Or should the target pickup the damage value from the weapon?

lapis atlas
#

hello

#

I wrote a parallex backgorund script, but UnassignedReferenceException: The variable cam of ParallaxEffect has not been assigned.
You probably need to assign the cam variable of the ParallaxEffect script in the inspector this error came up

rich adder
#

passes its values how much damage it does etc.

torn plover
#

To the IDamagable?
Currently what i was thinking, but was not sure what the best practice is

rich adder
#

I have IDamageable fire an event

#

then things like health component sub to it and receive amount in the params

slender nymph
torn plover
rich adder
rich adder
#

you can put a json string in playerprefs if its only settings but don't recommend using it @sage mirage
there is also a limit on how much you can store in PlayerPrefs, so a file is better(imagine using cloud saving to port settings acrosss devices)

slender nymph
lapis atlas
pliant raptor
#

hello, i'm working on a tutorial but something got weird really unexpectedly, as i was editing a separate class and i got the error "Look rotation viewing vector is zero
UnityEngine.Transform:set_forward (UnityEngine.Vector3)" on this line:

 float rotateSpeed = 10f;
        transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime * rotateSpeed);

anyone got this problem and know how to fix it??

rich adder
#

you must've rotated towards 0 at some point @pliant raptor

#

you can check if != Vector3.zero

#

iirc something to do with quaternions

wooden bay
#

Light2D only has additive and multiply I just want them the circle light to stack over the other one, and I don’t know what to do

pliant raptor
#

i think it worked! thank you! @rich adder