#💻┃code-beginner

1 messages · Page 513 of 1

remote kiln
#

i made a special tag for the obstacles for a reason

#

welp

#

oh i had a question, I have been facing this problem since the second i started scripting in unity

#

it doesnt show me errors in vs nor does it show me option that i can use

#

like Info.(displays info)

eternal falconBOT
remote kiln
rich adder
#

everything ? 🤨

remote kiln
#

well

#

yeah i js tried the extra ones i didnt try

#

everything is up to date

rich adder
remote kiln
#

where is that

rich adder
remote kiln
#

ah that

#

does it do anything when i click it, cus it did nothing visually

#

well either way, it didnt work

rich adder
#

screenshot the Solution Explorer view in VS

remote kiln
rich adder
remote kiln
rich adder
remote kiln
rich adder
#

do it on assembly, or try Load All projects there

polar acorn
#

I would recommend learning how to use a computer before attempting to make a game on one

remote kiln
solar orchid
#

Nah I think I got this ty anyway when people find out one guy made a game and he’s still super new to it and the games are amazing. They’re gonna be super surprised. : )

rich adder
languid spire
solar orchid
languid spire
#

rofl

solar orchid
#

What?

languid spire
#

have you ever heard the phrase 'The blind leading the blind' ?

solar orchid
#

No

#

Let me guess you’re gonna explain how I can’t use a PC if I’ve never used

#

and it’s gonna be in someway that looks like it was from a book

#

I mean sounds

#

Like a book

languid spire
#

no, I'm gonna say you have a great deal to learn. So much in fact that you have no idea of the time and effort it's gonna cost you

polar acorn
#

I'm just saying, learn how to use a device before trying to make a game. Game development is not easy and if you're completely baffled by the concept of computers it's going to be needlessly difficult.

#

I'm not sure at what level you'll need to start at but I can be sure that it doesn't start in a game development discord

solar orchid
#

I know how to do the basic things I don’t know why I said I don’t really know but I actually do sorry for the confusion like I know how files work I know how to open games turn the PC off turn the volume up I know how to edit files like I just know the basic stuff

minor whale
#

I hate this so MUCH. You cant change the pivot without ruining your prefab, you cant find the center of a empty, you cant center a pivot even if you change it. so WTF' AM I SUPPOSED TO do if I want to make my prefabed object move back and forth between a given object

#

I clearly cant fucking rely on pivot for the position

polar acorn
#

Make the prefab a child of an empty object, and position it where you'd want the pivot to be. Then move the empty

wintry quarry
#

you cant find the center of a empty
I mean you can but why would you want to

minor whale
#

I have to set the pivot to the center of the game objects

#

and thats not possible without guessing

wintry quarry
#

it just takes the average of the center of all the Renderers of the children

minor whale
#

so I cant find that vector anyway

wintry quarry
#

You can find it

#

I just told you how

polar acorn
naive pawn
#

isn't the "center" of an empty just its position lol

polar acorn
#

It has no extents. It's position is literally all of it. It's the center, the bounds, the extents, the top, the bottom, all of it. It's a point

wintry quarry
#

it's just the average of all the renderer bounds

minor whale
wintry quarry
#

It's not magic

wintry quarry
wintry quarry
polar acorn
#

Honestly you should probably not use the "Center" handle position in general.

rocky canyon
#

Pivot fo lyfe!

polar acorn
#

It's misleading and not useful at all for code purposes

minor whale
#

which is one way I was considering doing what I wanted

rocky canyon
#

or u use a empty object to mark the pivot.. and then move the transform to that position

#

uncalculated

polar acorn
#

If you need to change the pivot of something do what I first said and use an empty object and position that

minor whale
wintry quarry
polar acorn
# minor whale What?
  1. Create an empty object.
  2. Make your model a child object of the empty.
  3. Position the child such that the empty is at where you want the pivot to be.
  4. Boom you now have a pivot
minor whale
#

also one more issue is that I cant get the width of my game empty object without looping through all the children :0

wintry quarry
#

because "width of a GameObject" doesn't have any real meaning

minor whale
polar acorn
wintry quarry
polar acorn
#

Your issue is that you seem to assume that "this gameobject" means "this gameobject and all of its children" when that isn't the case

#

They're different game objects

#

they just have transforms relative to another object's

minor whale
#

Main issue was getting a prefab object to travel back and forth on a given object and a given axis

#

but then I kinda wanted to rant because everything I tried conveniently unity doesnt let you do without making you do it in a abstract or weird way when it has the features itself that define those already

wintry quarry
polar acorn
minor whale
#

yeah ik D: but it would be easier for me to do lol

polar acorn
#

This is what we call negative reinforcement. It wants you to deal with the pivot using a parent object, so it doesn't provide tools for dealing with pivots in other ways.

#

That way the position of the pivot is plainly visible in the inspector, instead of buried in the asset import settings or some other sub-menu

#

And you can quickly tweak it on the fly, even for different instances of the same prefab

minor whale
wintry quarry
#

then it's basically just:

Transform a, b;

void Update() {
  float duration = 2f;
  transform.position = Vector3.Lerp(a.position, b.position, Mathf.PingPong(Time.time / duration, 1));
}```
minor whale
#

lol

polar acorn
#

You'd put this script on your pivot object

#

then it'll move the object's pivot to exactly the position of a and b

wintry quarry
#

this is all solverd with a few seconds of setup and some small calculations in code

#

Game engines are meant to give you the foundation on which to build your game, they aren't meant to solve every individual problem automatically

minor whale
#

yeah but for a function built into the engine itself it would be nice if it was a feature in the documentation/api

polar acorn
#

Which function?

#

Lerp? Distance? Both are in the documentation

minor whale
#

this functionality on the front end of unity

minor whale
#

I meant the backend documentation

#

for scripting lol

polar acorn
#

Why would an interface feature be in the scripting documentation

#

There's nothing about "Center" mode in the scripting API because there is no such thing as the center mode in code

#

Code deals entirely with the true positions of the transform

#

When you do someObject.position that's getting you the position of the "Pivot" option from the interface, as the documentation I linked says.

rich adder
# minor whale for scripting lol

at most you can get the Center of a collider/ bounding box, but transform.position ALWAYS returns the pivot point center or not

polar acorn
#

"as defined by the Transform component"

minor whale
polar acorn
rocky canyon
rocky canyon
#

^ soooo fun

winter aspen
#

what's the consensus regarding using C# event over UnityEvent over Actions?
I expect to have data with my events, but no idea which to pick

polar acorn
#

UnityEvents can be set in the inspector.

That's basically it

winter aspen
#

what about Actions and C# events? (aside from the editor)
is there any reason to pick them?

polar acorn
#

An Action is an event, but with a specific pre-defined delegate

rich adder
#

Action is just a delegate type for event

#

use UnityEvent only when you need the inspector, period.

#

any other times use c# events

winter aspen
rich adder
#

this was done in unity 5.3.1f1 in 2016 , who knows how much is still relevant

winter aspen
#

Thanks

#

guess i'll just stick to C# events then

sturdy wharf
#

Hey everyone,

I’m working on a simple 2D game in Unity with a stickman character, where each part of his body (legs, arms, head, torso) has its own rigidbody, allowing for physics-based interaction. I currently have a script that lets me click and drag the stickman around, and he moves and interacts with the physics.

For a while, I was trying to create animations for the stickman to get up and walk, but since the game is heavily physics-based, I thought it would be cool to make the walking physics-driven too, kind of like in games like Totally Accurate Battle Simulator or Stick It To The Stickman.

The only problem is… I’m not the best at coding. So, I’m posting here to ask for advice or ideas on how to approach physics-based walking. If anyone has any tips, knows of any relevant tutorials, or even feels like helping out with the code, that would be awesome.

Thanks a lot!

wintry quarry
sturdy wharf
faint osprey
#
    {
        while(miniGameReadyToStart == false)
        {
            yield return null;
        }

        MiniGameIsReady?.Invoke();
        Debug.Log("woking");

        yield return new WaitForSeconds(3);

        for (int i = 0; i < players.Length; i++)
        {
            if(players[i])
            {
                localPlayer.transform.position = currentMiniGame.transform.Find("Player Spawn" + (i + 1).ToString()).position;
                localPlayer.GetComponent<PlayerMovement>().isSitting = false;
                localPlayer.GetComponent<PlayerMovement>().m_rb.isKinematic = false;
                localPlayer.GetComponent<PlayerSetup>().ThirdPersonCamTransition();
            }
        }
    }```

im invoking an event here after my while loop is over 

```    void Start()
    {
        TH = GameObject.Find("GameTable(Clone)").GetComponent<TableHandler>();
        TableHandler.MiniGameIsReady += StartMiniGame;
    }

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

    public void StartMiniGame()
    {
        Debug.Log("called");
        StartCoroutine(LavaTimer());
    }```

im subscribing to it here however the function never gets called. TH does get assigned so its not that and the object is instantiated before the event is called so i dont know what it could be
polar acorn
faint osprey
#

the function is never called

polar acorn
#

Which function

faint osprey
#

the one im subscribing the event to

#

StartMiniGame

polar acorn
#

Do you get the "woking" log?

faint osprey
#

yup

#

but not called

polar acorn
#

Then it is invoking MiniGameIsReady. Put a log in Start and see what order those happen in.

faint osprey
#

kk

#

ah

#

but thats odd

#

oh cause im instantiating it over the network it does it asynchrously which is why the start gets called after

#

makes sense

drifting cargo
#

!code

eternal falconBOT
drifting cargo
#
using System.Collections.Generic;
using UnityEngine;

public class ScopeOverlay : MonoBehaviour
{
    public GameObject scopeOverlay;
    public GameObject weapon;

    private bool isScoped = false;

    private void Start()
    {
        weapon.SetActive(false);
    }

    void Update()
    {
        if (Input.GetButtonDown("Fire2"))
        {
            StartCoroutine(OnScoped());
        }

        if (Input.GetButtonUp("Fire2"))
        {
            OnUnscoped();
        }
    }

    void OnUnscoped()
    {
        scopeOverlay.SetActive(false);
        weapon.SetActive(true);
        isScoped = false;
    }

    IEnumerator OnScoped()
    {
        yield return new WaitForSeconds(0.15f);  // Delay before scoping
        scopeOverlay.SetActive(true);
        weapon.SetActive(false);
        isScoped = true;
    }
}

#

so i have this script for a scope overlay for a sniper but i have to issues that i would like help with

#
  1. When i run the game the overlay starts on instead of off even though its set to false at start
    private void Start()
    {
    weapon.SetActive(false);
    }

  2. i only want it to work with my sniper curruntly when i press right click on any gun it will run this script and show the overlay on that gun.

rocky canyon
shell orchid
#

he is an enemy

teal viper
shell orchid
#

let me recheck

teal viper
teal viper
# shell orchid no

Then log the name of the object as well, and make sure you're looking at the right object.

shell orchid
drifting cargo
shell orchid
#

the thing i am clicking e on has teh right tag

teal viper
shell orchid
#

i give up

brittle prism
#

playerController.cs (controller in question)
cameraController.cs

  • I have movement relative to the camera.
  • Character is a ball

I want to stop my player from moving when the velocity of an axis falls below a certain threshold (and there is no input), but simply setting "velocity = 0" doesn't completely stop the movement.
In Line 121, using else if for both axes stops the movement after a few fixed updates, but it causes issues with jumping, making the player move along the X and Z axes (this only happens when the camera has been moved).
In Line 141, using else if for both axes stops the player momentarily (as seen only with Debug.Log), but then the player decelerates according to rigid body physics. Additionally, jumping does not affect the X and Z axes, which might be because the last else if is only called "once".

faint osprey
#

im trying to detect the trigger box collider on my child of my gameobject however neither of the debugs are calling. i do have a mesh collider on the parent gameobject howeever its not trigger so that shouldnt affect it no?

    {
        Debug.Log("collision");
        if (other.gameObject == trackedPlayer && inLava == false)
        {
            Debug.Log("collision with player");
            inLava = true;
            StartCoroutine(DeathTimer());
        }
    }```
rocky canyon
#

else it ignores it.. OnCollisionEnter would be called for a IsTrigger = false object

#

oh u said parent..

faint osprey
rocky canyon
#

does the actual trigger object have a collider?

faint osprey
#

the child has a trigger collider and the parent has a non trigger one

rocky canyon
#

have u tested w/o all the conditionals

faint osprey
#

wdym?

rocky canyon
#

to see if any collider triggers it

#

to see if its a trigger setup issue or its a failed assumption of conditionals

faint osprey
#

ill see

rocky canyon
#

ur Collision debug should fire tho

faint osprey
#

its not

#

even with the parent collider set to false

steep rose
#

does one of the objects have a rigidbody on them? iirc a trigger requires one

faint osprey
#

which collides with the colliders

drowsy oriole
#

This wont connect me to a new Photon room, can someone show me how to connect to the master server in this script https://hastebin.com/share/basopaciro.csharp

rocky canyon
# faint osprey yes the player has a rigidbody

i was going to ask.. does the parent object that has the child w/ the trigger use a rigidbody?
b/c for OnTrigger to propagate down the hiearchy it'd need one.. edit: (a rigidbody is what links all the colliders together, without one present they're all individual colliders)
if not then the code w/ OnTrigger functions would need to be on the component w/ the trigger collider

winter aspen
#

Does it ever make sense to have multiple unrelated finite state machines?
Ex: An FSM for player behavior (to handle movement, input game events, etc) and another for the GameManager (to handle level beginning, ending, mid-level events, etc)

keen dew
#

Yes, that's how it should always be instead of trying to cram everything into one massive FSM

upper forge
#

Any idea why my sprite in sliding when im making a cutscene using unity timelines???

teal viper
upper forge
#

I dont think so its weird cause i have used the same characters in 2 other cutscenes and they do not do slide then do the animation stuff.... its so weird

wild widget
#

Anyone can tell me why we use CompareTag ?
Compare tags with string equality ==. Use .CompareTag("Tag") instead.
from this
#💻┃code-beginner message

languid spire
fresh rivet
#

Hi im struggeling with assigning a function to my button

#

!docs

eternal falconBOT
naive lion
fresh rivet
#

No should i use a gameobject or can i just attach it directly to the button

#

because when i attach the script to the button I cannot use the public functions

naive lion
#

as in it’s not in the drop down ?

north kiln
#

Perhaps screenshot what you're trying to do

fresh rivet
#

Aah I found the problem

naive lion
#

o>

fresh rivet
#

I needed to attach the script to an empty gameobject

#

so that I could use it in my onclick() function

#

thank you sm

naive lion
#

yeah so it can find it

#

nws

#

gl with ur project

fresh rivet
#

thanks!

faint osprey
#

when i tab out of my game it runs at like 3 frames a second even tho i have application.runinbackground to true how do i fix this

faint osprey
#

cause like

#

if im tabbed our int general

#

both instances of the game run buttery smooth

#

but if im focused on one

#

the other runs like 0.3 frames a second

#

and my pc isnt strugglign so idk why this is happening

swift elbow
faint osprey
sturdy wharf
#

Hi,

I am trying to make an active ragdoll script, I was looking at YouTube tutorials but they all don't work on what I'm trying to do. see the ragdoll will be on the floor, in any state. I've made a ActiveRagdoll script (attached) but for some reason it does not work at all. (attached videos are with and without it). Anyone wanna help? 🙏 🙂

thanks

https://www.codebin.cc/code/cm2lcgr680001lj02zdx8bn67:A7zGuxs82FFi3YTaByZKfa16gGfUjmDw8MnNVAH66vGR

https://drive.google.com/drive/folders/19lbekOIBc34sMBDdHFGBPSPNBJRbRne4?usp=sharing

little meteor
random ravine
#

Hey, I'm making a 2d platformer, but I'm unsure on the movement code, I'm just using some code from a 2d rpg

rb2D.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized * speed * Time.deltaTime;

anim.SetFloat("moveX", rb2D.velocity.x);

how am I supposed to write this?

ivory bobcat
random ravine
#

I want it to be specificaly horizontal movement as I don't see any need for vertical movement (apart from jumpuing that I'm yet to learn)

ivory bobcat
#

Put zero for the second argument

#

Vector2(..., 0f)..

random ravine
#

cheers mate

shadow igloo
#

Hello, I'm new to coding and I have a problem with a bit of my code.
I have 2 different methods for 2 different tags, one for when player collides with different objects(tag), and one when he collides with the finish object(tag).
The colliders work fine(as the finish even transfers player to the next scene), but the problem is with the sound
The sound does play when I collide in the "StartCrashSequence" method, but not in the "FinishSequence", and I genuinely dont know why, because unity doesnt give me an error or anything, nor does VSC.
The sound files are present, both of them are working(tested by replacing the crash with the victory and bumping into objects, the sound worked)
what may be the cause for this?

ivory bobcat
#

Everything would be destroyed if so and thus no sound is played

shadow igloo
ivory bobcat
#

Make sure to save and try again. It should play if you haven't destroyed the scene (load etc)

little meteor
shadow igloo
little meteor
shadow igloo
ivory bobcat
#

Place a log in the function and see if it's logged into the console

shadow igloo
#

the collision works fine, however the audio isnt played. Audiosource is cashed at the start method

#

all other audio(crashing, boosting) works fine, audio for the finish line doesnt work, despite the rest of the code working

astral falcon
#

Just dumb suggestion, the sound is not empty, right?

shadow igloo
#

nope, it is indeed there

astral falcon
#

I mean the audiowave, you can hear it in another applicatino or in unity inspector

ivory bobcat
#

Did you do anything extra after playing the first audio clip? (such as pausing the source)

shadow igloo
shadow igloo
astral falcon
#

Can you debug log your victorysound?

ivory bobcat
#

You've mentioned that a few times but we're unsure what else you're doing

shadow igloo
ivory bobcat
#

Try playing that clip instead of crash initially

shadow igloo
teal viper
#

Can you also share the code with debug logs, so that we know that they're in the right place?

teal viper
ivory bobcat
ivory bobcat
ivory bobcat
#

So check your audio source before you finish and see if the component is disabled, object inactive, etc

shadow igloo
astral falcon
#

Also check for the audio listener to be active

eternal falconBOT
astral falcon
ivory bobcat
#

Did you save the scene? Maybe the reloaded scene doesn't have what you've got set in the inspector for the current edited scene.

#

Assuming reloading is a potential culprit

shadow igloo
#

because if i turn the scene changer again, the next scene will play

ivory bobcat
#

Comment out the invoke on reload and see if things change?

astral falcon
#

did you check on your audiolistener?

shadow igloo
astral falcon
#

and also check on the volume param of PlayOneShot

ivory bobcat
astral falcon
shadow igloo
astral falcon
#

!code

eternal falconBOT
shadow igloo
#

the finish uses LoadNextLevel which is commented out

ivory bobcat
shadow igloo
random ravine
ivory bobcat
#

Comment out the statements from crash and see if finish operates accordingly - you may need to force the finish to occur. I'm pretty sure if you simply call finish where crash was, it would work so crash has likely done something unintentional. Unless you've got something else going on in between.

muted pond
#

Hello i need help i dont know how to make an imported model collision

#

can someone help m?

#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

shadow igloo
ivory bobcat
shadow igloo
#

yes

astral falcon
#

so ignore the coroutine thing, just set the clip = victory and play it

shadow igloo
shadow igloo
shadow igloo
#

ok, i figured out why it was not happening, the tutorial i followed for this project mentioned we could ignore the "GetComponent<Movement>().enabled = false;" for the finish line if we want, so i did that, but that actually interfered with the audiosource playing due to it having an "else" statement that would stop audiosource from playing if the spacebar wasnt playing. Sorry for taking up your time and thank you all for trying to help me with it!

molten dock
#

for a save and load system, how should i manage the saving

#

the main way i have thought of is having the save button call something which activates every code block for each thing to save but idk how i do that

summer shard
#

hey, i need help with this stuttering movement. It only happens while moving the camera and moving the character at the same time.
This is the code

    [Header("Movement")]
    [SerializeField] private float moveSpeed;
    [SerializeField] private Rigidbody rb;

    [Header("Camera")]
    [SerializeField] private float sensitivity;
    [SerializeField] private Transform cameraHolder;
    private Camera mainCamera;

    //Singleton
    private static PlayerMovement instance;
    private void Awake() {
        if (instance != null && instance != this) {
            Destroy(instance);
            return;
        }

        instance = this;
    }

    private float cameraY = 0f;
    void HandleCamera() {
        float mouseX = Input.GetAxis("Mouse X") * sensitivity;
        float mouseY = Input.GetAxis("Mouse Y") * sensitivity;

        cameraY -= mouseY;
        cameraY = Mathf.Clamp(cameraY, -90f, 90f);

        cameraHolder.localRotation = Quaternion.Euler(cameraY, 0f, 0f);
        transform.Rotate(new Vector3(0, mouseX, 0));
    }

    void HandleMovement() {
        if (rb == null) return;
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");

        Vector3 move = transform.forward * vertical + transform.right * horizontal;
        rb.AddForce(move.normalized * moveSpeed);
    }

    void Start() {
        mainCamera = Camera.main;
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    private void Update() {
        HandleCamera();
    }

    private void FixedUpdate() {
        HandleMovement();
    }
stuck palm
#

is this the correct order for checking speed values in an if statement?

naive pawn
#

probably, yeah

wintry quarry
#
transform.Rotate(new Vector3(0, mouseX, 0));```
#

If you do this with a Rigidbody, it breaks interpolation

#

that leads to the stuttering you see

summer shard
#

ohh, how do i rotate the player then??

wintry quarry
summer shard
#

okay i'll try thanks

#

hmm after modifying, it stutters when i move the camera

wintry quarry
wintry quarry
summer shard
#
    void HandleCamera() {
        float mouseX = Input.GetAxis("Mouse X") * sensitivity;
        float mouseY = Input.GetAxis("Mouse Y") * sensitivity;

        cameraY -= mouseY;
        cameraY = Mathf.Clamp(cameraY, -90f, 90f);

        cameraHolder.localRotation = Quaternion.Euler(cameraY, 0f, 0f);
        //transform.Rotate(new Vector3(0, mouseX, 0));
        rb.rotation *= Quaternion.Euler(0, mouseX, 0);
    }
wintry quarry
#

hmmm... that should be fine 🤔

summer shard
wintry quarry
#

you have interpolation enabled on the Rigidbody yes?

wintry quarry
#

but it can be hard to tell from a video

summer shard
wintry quarry
wintry quarry
steep rose
# summer shard that's how it looks

what people usually do is move the camera to a position on your character instead of parenting it straight to the physics object, and they also use LateUpdate() for a smooth camera rotation as well.

summer shard
summer shard
echo sand
#
    public void OpenInventory(InputAction.CallbackContext context) 
    {
        if (context.started)
        {
            EnableUIMap();
            UIHandler.OpenInventory();
        }
    }

is there a way i can call my method without this forced parameter. i just want to use it outside of key bindings

slender nymph
#

take out the content of the if statement and put that into its own method. then call that method from within the if statement and from where ever else you wanted to

wintry quarry
#

context? yeah just make another method

echo sand
#

oh i see

steep rose
echo sand
wintry quarry
#

the if statement is not necessary

#

The parameter of course is still necessary because that's the delegate type the event expects.

The callbackcontext contains a lot more information than just the phase of the action

summer shard
steep rose
winter echo
#

when i switch to the 1st person view it gose to the side i put it the postion of the other camera

olive heron
#

At fridt glance, the code looks fine.

Maybe it's different expectations of your inspector values?

Go into playmode first, then set up the offset in the inspector window for both views, make sure they are how you want them to be, test by pressing C.

Changes aren't saved in play mode, so right click the component and choose "copy component"

Then exit playmode, right click it again and choose "paste component values"

terse oar
#

Hey, im about to start working on my new game, its gonna be a wow like third person fantasy game. Last time i did this i went with HDRP render and physics etc, i put the bar a bit to high, this time im going with URP and low poly stuff. Before i start with the player id love some input or ideas on what to go with gravity wise, physics or addforce. If i understand it correctly, physics can overcomplicate things, and very few games need it.

cosmic dagger
terse oar
#

oh then im mixing it up, i remember u could go with 2 different paths

cosmic dagger
#

maniuplating the transform or using physics . . .

terse oar
#

ah yes thats prolly what i was thinking about

#

i got pretty far on my last game but ended up in a very nasty problem with going downhill

#

i tried using raycasts and all sorts of stuff to detect the ground but it was a nightmare

#

was hoping there was an easier way

#

i should add that i cant code at all, i understand a few basics, learning as i go watching tutorials then having AI tell me what everythign does to understand it, so maybe its not that complicated to someone who knows what hes doing :p

cosmic dagger
#

detecting the ground is relatively easy. if you don't know coding i suggest learning C# basics, and following the unity beginner and intermediate programming pathways . . .

terse oar
#

im trying to stay away from premade stuff such as the game creator asset, i feel like making them urself even though if its together with a tutorial and AI it feels like its easier to expand it later on, not sure if im wrong

normal turret
#

Hey guys what's up...?

#

I know this might be a random question

#

But how would acceleration and friction work in Unity...?

#

I tried finding some tutorials, but strangely enough there's not a lot of tutorials that cover that topic

#

This is what I have so far, and...it doesn't work

languid spire
#

Firstly, please type in full sentences. Secondly exactly the same as irl using a Physics Material

normal turret
#

Oh so I just have to add a Physics Material to my RigidBody2D for the friction...?

#

What about for the acceleration, is it the same thing...?

languid spire
#

you have to create one and then add it, yes

#

acceleration is a mode of adding force, just like irl

normal turret
#

Ok nice, I'll try that out, thank you

coarse knoll
#

Im trying to do a tutorial someone is showing and they do myRigidbody.velocity but i cant find a .velocity

#

(im very very new)

slender nymph
#

it's called linearVelocity now

coarse knoll
#

ok thanks

languid spire
#

Unity 6 uses linearVelocity

polar acorn
coarse knoll
#

he uses .up tho and i dont see an option

#

do i just do vector?

polar acorn
languid spire
#

indeed, nice one Unity a breaking change for no discernible reason

polar acorn
#

There's a transform.up

#

but not a rigidbody.up

coarse knoll
#

im very new

#

rigidbody2d ig

slender nymph
#

being new does not mean you don't have to read what the tutorial shows. there is no linearVelocity.up

languid spire
#

i'm sure your tutorial, no matter how old, did not do that

coarse knoll
slender nymph
#

yes, now read that

coarse knoll
#

theres a possible chance

#

possible

#

that i put a . instead of =

polar acorn
#

Just use linearVelocity instead of velocity

coarse knoll
#

mb

#

also

#

when should i be putting a ; at the end of a line

languid spire
#

I think you need to learn some C# basics

coarse knoll
#

thats what im doing rn

#

sortve

slender nymph
#

you're skipping the "learning c#" part and trying to go straight to the "learning how to use unity" part

coarse knoll
#

i used to do a little lua

#

ill check out a video of the basics rq

languid spire
#

do you know when to use a full stop in a sentence?

coarse knoll
#

nope

languid spire
#

so you've come here looking for grammar lessons?

coarse knoll
#

i just clicked the first "basics of unity" video

burnt vapor
coarse knoll
#

im not even half way through so he could possibly explain everything

burnt vapor
#

I swear they don't use their own application

burnt vapor
#

It's not even about that this type of help should not be needed

coarse knoll
#

alright

burnt vapor
#

You should seriously consider learning the basic concepts of C# before you start using Unity alongside it

#

Because now you learn two massive things at once

coarse knoll
#

can you recommend a video rq?

rich adder
coarse knoll
#

alright thanks

rich adder
coarse knoll
#

ok

languid spire
zenith cypress
#

Doesn't take much to search&replace across a codebase then fix the rest 🤷‍♂️ And if you don't need a new feature, then don't upgrade anyway.

polar acorn
#

It's weird that velocity got, like, instantly axed as soon as it was replaced, but renderer, collider, etc. existed for like fifteen years without actually functioning

slender nymph
fossil axle
#

what does this mean?

#

"A Native Collection has not been disposed, resulting in a memory leak."

slender nymph
#

is this error even related to your code

ruby python
#

Can anyone see what/if I'm doing wrong with this collision script please? I'm very confused.

Asteroid Tag is correct, asteroiud object is assigned the correct tag. The actual collision(s) work (ship hits the asteroid and stops etc), but the OnCollisionEnter isn't firing at all. Ship Root object has a Rigidbody, no rigidbody on Asteroids and necessary colliders are set as colliders (Not Triggers)

private void OnCollisionEnter(Collision collision)
{
    Debug.Log("Hit");
    if (collision.gameObject.CompareTag("Asteroid"))
    {
        
        shieldMaterial.SetFloat("_Alpha_Level", 1);
        StartCoroutine(ShieldFade());
    }
}
fossil axle
#

no

ruby python
#

The Debug isn't firing at all.

fossil axle
polar acorn
ruby python
polar acorn
grave bluff
#

Are you using cinemachine camera?

ruby python
#

Shield Segment Object

grave bluff
#

Your player is being moved in fixed update but the cinemachine camera is probably set to smart update or some thing

#

Set your cinemachine camera to fixed update

ruby python
#

Ship root (with RigidBody) (Box collider is for something else)

grave bluff
#

Ok but what about update method that’s still on smart update

#

What happens if you set update method to fixed update

polar acorn
ruby python
#

Asteroid

#

The Shield Segment has the code/script applied.

grave bluff
#

Are all your cinemachine framing stuff set to default

polar acorn
# ruby python Asteroid

So, this is a third different object. Which of the two you've shown before is the one colliding with this object?

ruby python
#

First one I showed is the Shield Segment object (I have 4 of them, only testing with one at the moment).

grave bluff
#

Yea I think it’s in the brain

ruby python
#

Second one I showed is the 'Ship Root'

grave bluff
#

You know how you can set the damping and offset and all that stuff

ruby python
#

3rd is the asteroid.

zenith cypress
polar acorn
#

Which two are the objects that are actually relevant to this collision? The one with the code on it, and the one that's touching it

ruby python
#

Just to show that the ship has a rigidbody

grave bluff
#

Ok new idea what if you set the update method to late update

ruby python
#

Okay.

Shield Segment, which has the collision code attached.

#

Asteroid Object

grave bluff
#

Just update method

#

Man

polar acorn
grave bluff
#

Is it just the background that’s jittery and the player is perfectly fine and in frame

ruby python
grave bluff
#

Is the background static or moving as well

#

That’s weird

#

Ok I’ll see

polar acorn
# ruby python Shield Segment has the code.

Ah, okay. That would be the problem. The Rigidbody calls the function on itself, and the object it hits. So, even though this object's collider is part of the rigidbody, it won't actually send a message down to this object. It's detecting the collision, but it's not getting the function call.

zenith cypress
#

Collision events have to be on the rigidbody yeah ^

#

Had to verify locally since I always forget if that is the case lol

polar acorn
zenith cypress
#

Yeah

ruby python
#

Right okay. I get ya. I was reaaaaaaaaaaaaaaaaaaaaaaally trying to avoid having rigidbodies on the asteroid.s 😕

edgy prism
#

!code

eternal falconBOT
ruby python
#

I guess it would be more efficient to add rigidbodies to the shield segments and set them to kinematic?

polar acorn
#

You could have the Asteroid check if the thing it collided with has the ShieldController script, and if it does, call a function on it that does what you need it to do

ruby python
#

Right okay. Yeah I think that would make more sense.

#

Thank you 🙂

#

This might be a really stupid question, but in terms of referencing other scripts on different objects etc. When it starts to get to be a lot, how do people keep track of all the 'cross referencing' ? I try to avoid it as much as humanly possible cause it gets really confusing after a while. lol.

zenith cypress
#

Could also have the event on the Player's rigidbody, get the contact point, check if it has the shield collider in the contact point, then pass the same collision to a function on your shield to do the same logic you have now.

edgy prism
#

Hello I am working on a project with projectile spawns and I am currently spawning them probably pretty poorly, my problem comes when I go to destroy my projectiles, if I do so before the coroutine that handles their logic finishes I get missing reference errors but I'm not really sure of the best way to deal with that.

Heres an example of one of my coroutines
https://hatebin.com/qcvwscppna

dim yew
#

how would you go about interpolating the color of a sprite renderer so it becomes invisible after a set period of time?

#

i'm thinking slerp would be the best way but i really cannot figure out lerping

dim yew
#

coroutines notlikethis

#

alright thanks

naive pawn
#

you would lerp from 1/255/100 to 0 on the alpha channel

zenith cypress
rich adder
edgy prism
#

Dotween can be super useful for stuff like that if you want to lerp the alpha a specific way too

dim yew
#

i guess i just need to do more research on lerping also

zenith cypress
#

It's basically the modern dotween, highly recommend it (I use it in all my projects)

winter echo
dim yew
#

i'm not familiar with dotween actually

#

so i have some reading to do

rich adder
#

its very good tween library

#

incase you want to use just lerp/coroutine

IEnumerator LerpAlpha(float target, float duration)
{
    float t = 0;
    var startcolAlpha = spriteRenderer.color.a;
    var col = spriteRenderer.color;
    while (t < duration)
    {
        col.a = Mathf.Lerp(startcolAlpha, target, t / duration  );
        spriteRenderer.color = col;
        t += Time.deltaTime;
        yield return null;
    }
    col.a = target;
    spriteRenderer.color = col;
    //done
}```
wrote on phone so maybe a mistake in there but example should be ok 😛
grave bluff
#

Lerp will answer that

rocky canyon
#

how is that weird?

dim yew
#

i've been trying to figure that out for like an hour

rich adder
#

its the ratio between 0-1

grave bluff
rocky canyon
#

my gas tank hold 13 gallons.. my gas gauge tells me theres 6.5 gallons if its on half a tank

grave bluff
rich adder
rocky canyon
#

10/20 would come out to 15, if .5 for t

#

and so on.. cant type today..

grave bluff
#

Yea

rocky canyon
#

i use dotween tho..

#

@zenith cypress is prime really better?

grave bluff
#

What’s T% of the way between A and B

#

That’s a lot of deltas in your username bro

rocky canyon
#

facts

edgy prism
zenith cypress
rocky canyon
#

okay.. im sold.. DoTween always worries me what its doing in the bakground

rich adder
#

need to try this myself, was using dotween for a while when I'm not doing it with a coroutine

grave bluff
rocky canyon
#

when it makes sense.. ofc

grave bluff
#

Anyway. StopCorourine might solve your issues

dim yew
#

or am i silly

rocky canyon
#

if a = 50 and b = 90 yes

dim yew
#

ok cool

#

thanks everyone

zenith cypress
rocky canyon
#

ohh no.. lol

zenith cypress
#

Just don't be goofy hehe

rocky canyon
#

i'll try

#

installing now 👍 lets give it a whirl

edgy prism
edgy prism
rocky canyon
#

exactly.. it never really matters if it functions

#

its all about scaleability, readibility/writeability and common courtesy for others to read it

grave bluff
#

Also, comment your code

rocky canyon
#

if u come back to it later and want to update.. its only yourself thats gonna shoot urself in the foot

grave bluff
#

Please 😭

rocky canyon
#

XML

edgy prism
grave bluff
#

3 comments for over 100 lines of code doing a lot of different things

edgy prism
grave bluff
#

It’s very disorienting

grave bluff
rocky canyon
#

just write urself notes

grave bluff
#

Like why these positions are being changed or what this temp variable is doing or what’s controlling who

rocky canyon
#

write what things do.. how variables are storing data, how things communicate etc

zenith cypress
#

I write comments if I actually have to, otherwise I just have readable apis, and I group the code inside of those functions in context-specific blocks.

rocky canyon
#

#regions?

zenith cypress
#

No I don't use those

grave bluff
#

Basically like if you had to explain it to a professor during a presentation for a final project

#

Although I’ve never had to do that yet so idk what that’s actually like

edgy prism
grave bluff
#

In my head I’m imagining a book report presentation but on your own code lol

rocky canyon
#

all can be important

zenith cypress
#

this is what I mean by blocks @rocky canyon

edgy prism
#

I feel like im 90% of the way there just by reading the code itself I suppose its just like spawn camp says its about speeding things up and being courteous to others that might see it

rocky canyon
#

book report/ documentation, tomato, tomato

rocky canyon
#

pretty easy to just do that

rocky canyon
edgy prism
#

Ill make an effort to try and add some more comments going forward too im sure my future self with thank me for it, and thanks everyone for your inputs you're the best.

rocky canyon
#

i like how ur code fits in a narrow width margin

zenith cypress
#

It makes quick scanning very easy

rocky canyon
#

var monster

winter echo
#

i have question how to do a local multplayer if there any videos to help me

rich adder
#

If you mean LAN, thats no different than doing it over the internet. Over the wire is over the wire, in that case any of the NGO series would work for example

karmic isle
#

hey so its been a while, im trying to get my character to jump, heres my code so far. I get an error that says "'Rigidbody2D' does not contain a definition for 'Addforce' and no accessible extension method 'Addforce' accepting a first argument of type 'Rigidbody2D' could be found"

Anyone know a way I can fix this?

eternal falconBOT
rich adder
#

and you should listen to the compiler more. It 99.5% percent tells you the truth

willow scroll
rich adder
#

don't just fix the spelling error and move on, actually configure your IDE for starters

rocky canyon
willow scroll
#

That's why I have pointed out configuring the ide after mentioned the actual mistake

karmic isle
#

im using the new coding system for visual code and im honeslty still getting used to it

#

its also been a few months

#

intellisense isnt even working and ive enabled it I believe

rich adder
#

its not enabled, I could see that in the screenshot.

#

it would underline red if it was

karmic isle
#

oh

rich adder
#

when you use the . operator, you would get a list of all of methods in that class

karmic isle
#

do you know how to enable it in visual studio code?

rich adder
karmic isle
#

will do

#

thx homie

rocky canyon
#

i think its the DevKit that does it ultimately

rich adder
#

if you followed all the steps and still have issues, well check it out

#

usually its SDK missing.. still broken in install process

rocky canyon
#

that too..

rich adder
#

for Linux Mint + unity 6 setup vid I yesterday and it happened right away, as soon as SDK 8 was installed intellisense worked again

#

its kinda sad the automatic processfails

rocky canyon
#

it gives u that popup warning..

#

thats a pretty solid dialog window

#

just "Get SDK"

rich adder
#

yep. Just wish it was installed with C# devkit or something

noble lark
#

Hello! I have a question regarding velocity of rigidbodies. I currently have a script that controlls the player with force mode VelocityChange. However when changing direction it feels kind of awkward and almost missaligned from where I want to turn towards. I know why this is happening but I'm confused about how I should counteract the force being applied in one direction when I change to another direction. This is my code and the important details for the player prefab: https://pastie.io/tkrjbw.cs

rocky canyon
#

cancel out all ur velocity and then apply the other direction

noble lark
#

Yes, thats what I tried doing but what I'm mostly confused about is when I should do this. The direction vector is not cooperating the way I thought it would. It's a silly problem really

#

Actually ill try one more thing before I ask for more help

elder fern
#

Hey guys, im new to unity so sorry if this is dumb, but on my laptop i just updated to unity 6, and now my ui and buttons isnt working. I used the legacy buttons

#

Thanks for help

rich adder
noble lark
#

Okey it almost works but I still run into this issue that I dont quite understand, sometimes after turning the character keeps holding a direction that is not the new one for way longer than it should until new input is given. This is the new code, I'm really tired atm so I'm probably missing something obvious? https://pastie.io/ywzkbv.cs

waxen adder
#

How do people back up their projects? Right now, all I'm doing is using a usb I have lying around XD

rocky canyon
#

!vc

eternal falconBOT
#
Using version control in Unity

Unity Version Control

git Git

Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.

waxen adder
#

Github sounds like a good idea, now that I think about it

karmic isle
#

Man i really hate that there are multiple ways to do the same thing in unity, its confusing most times

rocky canyon
#

nature of a game-engine and having full reign

#

same thing applies to life

rich adder
rocky canyon
#

if there was only one way of doing things games would literally be identical..

wanton fjord
#

Hey 🙂

I need a code review, I don't know if this is the best way to do it so I'd rather have an opinion
Im creating an Objective system, like a Quest system, but im pretty sure im using a bad way to do this

My current problem is i need to access the CircuitBreaker instance from the CircuitBreakerObjective to know if the objective is completed
So at the start of the game, i need to get all GameObject's in the scene that have a derived Objective component and register them randomly as an Objective to complete

CircuitBreaker and CircuitBreakerObjective are added on the same GameObject

There is a better way to do that ?

public class CircuitBreaker : MonoBehaviour, IRepairable, IInteractable
{
    // Logic ...
}

[RequireComponent(typeof(CircuitBreaker))]
public class CircuitBreakerObjective : Objective
{
    private CircuitBreaker _circuitBreaker = null!;

    private void Start()
    {
        _circuitBreaker = GetComponent<CircuitBreaker>();
    }

    public override bool IsCompleted()
    {
        if (Info is not CircuitBreakerObjectiveInfo info) 
            return false;
        
        return _circuitBreaker.IsOn == info.MustBeOn;
    }

    public override bool IsFailed()
    {
        // TODO - Add circuit breaker failure
        throw new System.NotImplementedException();
    }
}

Objective:

public abstract class Objective : MonoBehaviour
{
    [field: SerializeField] public ObjectiveInfo Info { get; private set; } = null!;
    [field: SerializeField] public ObjectiveState State { get; private set; }

    public PlayerPawn Owner { get; private set; } = null!;
    
    public abstract bool IsCompleted();
    public abstract bool IsFailed();
    
    public void MarkAsCompleted()
    {
        State = ObjectiveState.Completed;
    }
    
    public void MarkAsFailed()
    {
        State = ObjectiveState.Failed;
    }
}
noble lark
#

I solved my problem but I was wondering if there is a better recommended approach to solving this problem or if this is fine? I was having trouble with changing directions smoothly using VelocityChange force mode. This is the code: https://pastie.io/rccjfk.cs

vestal adder
#

making the rigidbody interpolated will stop the blur probably

#

i think the pixel snapping isnt helping

dusty shell
#

How do I know which colliders are colliding for a humanoid gameobject?

vestal adder
#

try removing that and the code for it and see what its like

#

You dont want to do all your logic in fixed update, only the rigidbody stuff

vestal adder
stuck field
#

No, I'm just asking you to test it basically

#

See if that works then we can go from there because we know where the issue is

dusty shell
stuck field
#

Comment out your FixedUpdate and put rb.transform.Position = Vector2.Lerp

#

inside update

#

under movement

#

Well, Vector2.Lerp smoothly moves from one Vector2 to another

#

So you need the target position to move to, rather than movement

#

No, Vector2.Lerp(CurrentPos, TargetPos, moveSpeed)

#

Current pos would be rb.transform.position

#

Target pos would be wherever you are trying to move to

#

no, rb.transform.position

#

or if rb is on the transform

#

then do transform.position =

rocky canyon
stuck field
#

Yeah look at that might help

rocky canyon
#

you shouldnt include the thing ur lerping into the lerp..

#

it'll not work right..

vestal adder
#

did you go to your pixel perfect camera and turn off pixel snapping

#

yes if pixel snapping is on it will be jittery

#

i just tested it with my own pixel game

rocky canyon
#

gotta make the player move the distance the camera snaps/travels for it to look smooth

vestal adder
rocky canyon
#

i think his collision code is on the humanoid

vestal adder
#

ill give you my player movement then you will be able to tell if its the code

dusty shell
rocky canyon
#

not sure how u could tell which collider collides

#

unless u have code on each one

#

or ur collision gets flipped and the thing its colliding with is the thing detecting the collision

#

then u could ask what other. is

#

and that'd be the collider of ur humanoid that di dit

dusty shell
#

I have seen some ways but i just wanted to know if i could get which collider is colliding

rocky canyon
#

put the grounded code on the feet specifically? loll

vestal adder
#

using UnityEngine;
using System.Collections;
using UnityEngine.InputSystem;

public class Movement : MonoBehaviour
{
public float moveSpeed;
public Vector2 input;
private Animator animator;
private Rigidbody2D rb;

private void Awake()
{
    animator = GetComponent<Animator>();
    rb = GetComponent<Rigidbody2D>();
}

private void Update()
{
    
    // player input stored in input variable
    input.x = Input.GetAxisRaw("Horizontal");
    input.y = Input.GetAxisRaw("Vertical");       
}

private void FixedUpdate()
{    
    rb.velocity = input.normalized + new Vector2(input.x, input.y) * moveSpeed;   
}

}

rocky canyon
#

same issue comes up w/ regular composite colliders (one rigidbody and multiple colliders as children)

#

the only good way is to run code on each collider, or have something else check

#

theres dozens of Unity Discussion posts about it

#

so they can see it changing in the inspector ofc

vestal adder
#

its just an oversight

#

it can be private

#

i like velocity it feels smooth

rocky canyon
#

velocity always better than movepos imo

#

when dealing w/ physics.. do it right ykno?

vestal adder
#

mine is topdown

rocky canyon
#

see if it works for you.. tryitandsee

#

ur only normalizing part of ur vector

#

then u add a (non)normalized part of it back to it

#

this is not normalized.. u only temporarily grab a normalized version of input there at the beginning

#

you should probably change the whole variable before using it..

dusty shell
rocky canyon
#
    private void Update()
    {

        // player input stored in input variable
        input.x = Input.GetAxisRaw("Horizontal");
        input.y = Input.GetAxisRaw("Vertical");

        input = input.normalized;

    }```
#

why not normalize it after u get it??

#

and then u can just use input and input.x or y

vestal adder
#

I dont increase speed when going diagonal in my game

rocky canyon
#

both would be normalized...

#

i told u why..

#

if u dont normalize the entire variable u should do
rb.velocity = input.normalized + new Vector2(input.normalized.x, input.normalized.y) * moveSpeed;

#

yea..

#

does it still move diagonally faster?

#

well. i wasn't talkin about the jitter.. i just noticed that bad normalization

#

not sure how to fix ur jitter issue

#

its in fixed update..

#

it should be consistent

#

maybe its the pixel / camera stuff

#

i dont know about any of that unfortunately 🍀

#

if the background is snapping it makes sense in my head..

#

so the background and player would snap together

#

then it'd look smooth.. (atleast the background wouldnt jitter against the player) then again idk

vestal adder
quartz beacon
#

in the new input system, how can i make it so instead of it just snapping to -1 and 1, to gradually increase and decrease like in the old system?

dusty shell
vestal adder
#

im not sure what it being a humanoid rig changes

rich adder
quartz beacon
#

or instead of a 2d vector

rich adder
dusty shell
solar orchid
#

Unity’s almost done downloading I can finally make my dream game if you wanna give me ideas you can. It’s a survival base game with a teeny bit of horror like ark survival evolved

solar orchid
rich adder
#

just rename the folder

#

the rest is done in Player Settings for the final build

solar orchid
#

Can someone please tell me where I can open my project? Plssssss

rich adder
solar orchid
#

Sorry, but I need help

rich adder
#

so what? post in the proper channel

solar orchid
#

Stop beefing with me

vestal adder
#

so are you trying to make a characters hitbox

#

and tell when it is attacked

dusty shell
eternal falconBOT
solar orchid
#

Gn

polar acorn
# solar orchid What?

Well, this is a channel for getting help with code. If you're asking a question here there should be code to show

vestal adder
#

private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{

    }
}
dusty shell
#

I have a blend tree that controls my character's speed based onthe speed of the player. I want to add a jump to the character and have no idea how to start the animations

prime goblet
#

i'm having an issues appending data to an array, there's an error:
Assets/Scripts/CubeManager.cs(31,24): error CS1061: 'Cube[]' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'Cube[]' could be found (are you missing a using directive or an assembly reference?)
Here's the code:

file.Cubes.Add(new Cube(cube.name, cube.transform.position, cube.transform.rotation));

here's where file.Cubes is defined:

[Serializable] public class Cube {
    public string CubeName;
    public Vector3 Position;
    public Vector3 Rotation;
}
wintry quarry
#

They are of a fixed size

#

If you want a data structure that can be appended to, you want a List

#

In this case, List<Cube>

#

(the definition of Cube isn't relevant to this problem)

tulip pilot
#

good morning folks

#

I need some help here

#

I'm trying to add a Line graph to the my Runtime UI. The graph will Scroll along with the Game and display a Line plotting the Torque and Power Consumption of a Motor agaisnt one another

prime goblet
#

although there is another issue,

file.Cubes.Add(new Cube(cube.name, cube.transform.position, cube.transform.rotation));
wintry quarry
#

Maybe you wanted to use an object initializer?

prime goblet
#

how can i do that?

wintry quarry
prime goblet
#

i finished that course but i did forget some stuff which i didnt use very often

#

i'll review it

eternal needle
#

although that partly sounds like a ui question instead of code question

wild widget
#

!vc

eternal falconBOT
#
Using version control in Unity

Unity Version Control

git Git

Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.

wild widget
#

!vs

eternal falconBOT
#
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)

prime goblet
#

!ide

eternal falconBOT
tall spade
#

!code

eternal falconBOT
spice girder
#

How can i destroy this object if it hits nothing?

#

after a short amount of time

rich adder
spice girder
#

But the time is 5f. The Destory object has that as a second property

rich adder
#

so move it in Start or Awake

near wadi
#

you sure?

#

oh, i see your logic. cool (one of these days i will learn c#) :/

spice girder
spice girder
#

I even put it at 1 sec

rich adder
#

you only need 1 btw not both

spice girder
rich adder
spice girder
#

I'm such a clown. That's the problem. I didn't put the script on the prefab. Sorry for wasting your time

#

rookie mistake

rich adder
#

it happens

spice girder
#

thanks for the help

near wadi
#

so that works because the bullet doesn't run its Start or Awake until Instantiated?

rich adder
#

indeed

near wadi
#

cool deal, thanks both

hasty tundra
#

Im trying to detect all colliders within a small range of this object, but no matter how high i set the CheckRadius variable, it cant detect any colliders. This is my first time using the OverlapSphere Function, so theres a real chance im just using it wrong. (The games 2d so if thats a 3d specific thing or something thatd be why 😭 ) Any help appreciated

wanton fjord
#

Use Physics2D class instead

#

If your game is 2D

hasty tundra
#

Thought itd be smth like that, thanks 👍

hasty tundra
wooden sandal
#

how can i manage to sort the list in the correct order?

#

i tried
previewSpriteList.Sort((a, b) => a.name.CompareTo(b.name));
and
previewObjectList.OrderBy(g => g.ID);

#

does nothing

#

the sprites are loaded from resources folder already in this binary sorting

burnt vapor
#

What is the thing to sort? Share your !code

eternal falconBOT
burnt vapor
#

Considering sorting depends on complexity and types in general there's no answer to give until you tell us what it is you want, and what you work with

wooden sandal
burnt vapor
#

That's still too vague

#

What sprites? Show their names, show the folder itself

wooden sandal
#

they are called level 1 to level 11

burnt vapor
#

Show how you currently load them

#

Show code

#

If you want to sort by name, I suggest you try to parse the level number and then sort numerically

#

Hardcode a check that gets the 6 and 7th number and then parse these as an integer. Make sure to check the length. Then keep track of the names and sort based on the number

elder fern
burnt vapor
#

Or don't make it complicated and figure out the number of sprites you are going to display

sleek narwhal
#

I am using this code in to check the collision between two physics bodies, but it's not printing to the terminal when they collide void OnCollisionEnter(Collision collision) { UnityEngine.Debug.Log("Entered collision with " + collision.gameObject.name); }

burnt vapor
#

If you have level 1 to level 11, then you have 11 sprites. Then just use a regular for-loop using this length

teal viper
#

At least not the object that has this method.

burnt vapor
echo sand
#
public interface Interactable
{
    public void Interact(Player Player);
    public virtual string GetHoverText(Player Player) { return "Use"; }
}

is it possible to override "GetHoverText" in my interface,
i want the default return to be "use" unless i want to use custom logic and return other strings

teal viper
#

You don't need virtual keyword though. Interfaces are not classes.

echo sand
#

lol i asked chatgpt

burnt vapor
teal viper
#

Ah, perhaps that feature(default interface implementation )is not supported in unity yet.

burnt vapor
#

If you want this, use an abstract class

#

Modern C# has support for base implementations, but not like this

#

And especially not in Unity

burnt vapor
echo sand
#

ohh that would work

burnt vapor
#

Or maybe call it IHoverMessageProvider since you will still show a hover message, but it provides a custom message

noble lark
#

Hello, I was wondering why the direction is not properly updating when trying to move my character. I take my direction from a center point on my character (i grab the forward and right vector of the characters transform). This is the code: https://pastie.io/jbeyls.cs

#

I tried to get help with this yesterday but the response was lacking

native temple
#

not to backseat moderate but I don't think it's appreciated to post the same question across all three code channels c:

burnt vapor
#

It's not, that's not the purpose of the channels

noble lark
#

Is pastie io frowned upon on this server, is that why almost everybody ignores the question?

native temple
#

how does your camera follow the player at the moment?

burnt vapor
slender nymph
#

9 times out of 10 it's caused by the camera's movement

noble lark
#

thats why i asked

#

ill stay away from pastie and use code blocks instead until i know

burnt vapor
#

Hard to give an answer when you share a whole class without a direct indication on where one should look

noble lark
#

that was just a test to see if it was gonna get ignored again

burnt vapor
#

What is relevant where? Where is the code that fails? Got a video perhaps?

#

So you don't need help?

noble lark
#

I do, ill repost the message i sent yesterday then

native temple
#

how are you ensuring this?

#

is your camera a child object of the player? is the camera setting its position in Update? In FixedUpdate? is the camera following with smoothing? is it a standard unity camera or a more complicated camera rig?

#

is your game physics heavy?

shrewd oak
#

i need help with my passport game pls

slender nymph
eternal falconBOT
native temple
#

then the easiest solution for now would be to change FixedUpdate to Update and use Time.deltaTime instead

wintry quarry
#

MovePosition doesn't belong in Update

#

really for a dynamic body you should use velocity

#

velocity

#

not MovePosition

#

rb.velocity = movement * moveSpeed;

native temple
wintry quarry
#

Although it's possible I'm confusing how 3D works with 2D

shrewd oak
#

tbh i would ask chatgpt

native temple
#

the jittering happens because physics framerate is at 50 fps by default, while rendering framerates are usually unlocked, or vsynced at 60

shrewd oak
#

skibidi cap

native temple
#

the lazy solution is to increase your physics framerate, but that will hide your issue rather than fix it

#

yeah

#

set it to 0.01 and you probably won't notice issues

#

0.02 is 50 fps, 0.01 is 100 fps

#

if your monitor refresh rate is higher than 60Hz then you might still see the jitter

#

(hence it would mostly hide the issue and not fix it)

#

so, in theory, as long as the rigidbody is set to interpolate, cameras following it should be able to smoothly follow, so that's one more thing to check

#

(might not mean it does so in practice)

#

another solution is to smooth the camera movement, which can also help reduce the issue a little bit

noble lark
#

Hello! I have a question regarding velocity of rigidbodies. I currently have a script that controlls the player with force mode VelocityChange. However when changing direction it feels kind of awkward and almost missaligned from where I want to turn towards. I know why this is happening but I'm confused about how I should counteract the force being applied in one direction when I change to another direction. Another problem that might or might not be related is that the code works perfectly when i look down as much as possible. This is my code and the important details for the player prefab: https://pastie.io/swoycv.cs

frank flare
#

Hopefully this uestion doesn't sound like a bunch of random words (I tried)

I want to make the player similar to Human Fall Flat but I'm not sure how. (Human Fall Flat is on the image)

  • What I want:
    1 - I want the player camera to be in 3rd person (just like in human fall flat).
    2 - The player character to be able to rotate from vector y to x or z
    3 - In 2 I want the player character to aim for the straight position by forces

  • uestions of implementing:
    How can I make the player camera be in 3rd person (I want the camera to be in the back and just like in Human Fall Flat 15 degrees down)
    How can I make the player to aim up on y vector? (while writing I understood I can PROBABLY just apply constant forces up on y vector on the player's head but currently as a first step I'm having problems with making the player to be in 3rd person because I can't do it by messing around.)

Code that I currently have for movement:
PlayerMovement: https://hatebin.com/nbbmviywid
PlayerCam & MoveCamera: https://hatebin.com/kdermrhkac

Edit: ok somehow I got it to be 3rd person rn, apparently I didn't mess around enough

steep rose
# frank flare Hopefully this uestion doesn't sound like a bunch of random words (I tried) I w...

human fall flat does not use traditional movement techniques, it uses an active ragdoll which is modified to use forces to "tug" limbs in a certain direction giving it the stylistic feel instead of physical animations. The balance is achieved by locking the rotation of the hips so it cannot fall down, if you would like it to fall down you would need to implement your own balancing system which compromises of setting the rotation of the hips to match a certain angle, then apply logic if you want it to fall down like a ragdoll. Third person is self explanatory, rotate a camera pivot to achieve a Third person effect, or you can use cinemachine which I heard most people recommend.
Here is a guide on a traditional active ragdoll, which contains the basic premise of one.
https://www.youtube.com/watch?v=HF-cp6yW3Iw&t=538s&ab_channel=SergioAbreuGarcía

This is all I learned while making active ragdolls in Unity. I hope you find it useful or, at least, interesting :D

The actual tutorial: https://bit.ly/3lKsfk2
Github repository: https://bit.ly/2VxnU98

----- Social -----

Twitter: https://twitter.com/sergioabreu_g


Ambient Generative Music by Alex Bainter [generative.fm]

-...

▶ Play video
severe onyx
#

so Im currently using a method called OnMouseDown() do execute certain code when I click on a specific 3d object; how would I go about adding another function for when the object is clicked and then the mousebutton is held down for a certain amount of time?

severe onyx
#

seems like OnMouseDrag was what I was looking for, I just misunderstood how to use it whoops

naive lion
#

!code

eternal falconBOT
minor whale
#

it would be pretty funny if mathf.pingpong actually is real

wintry quarry
#

You think I'm just making stuff up?

minor whale
#

nah just wanted to make sure that matched what I thought it was doing

wintry quarry
#

Look up what the function does and/or try it out.

minor whale
#

but what is the 3rd parameter even usualy do in that case

#

4th*

wintry quarry
#

There is no 4th parameter. When you have a question like that, you should be looking at the docs

#

they explain everything

minor whale
#

oh wait mis read the code

#

slerp and lerp are used differently how again?

polar acorn
wintry quarry
#

slerp is for directions, lerp is for positions

minor whale
#

one was rotation I thought

#

so slerp rot

wintry quarry
#

slerp direction vectors (which results in rotation of those directions)

minor whale
stray iron
#

Guys i want to add multiple instances of a prefab Button through c# but i don't know how to set it as a child of canvas

frosty hound
#

The Instantiate function takes in a parameter for the parent

wintry quarry
willow scroll
wintry quarry
#

it will mess up all the layout

#

Instantiate(myPrefab, theContainerTransform) is the best way

willow scroll
wintry quarry
#

because it does

#

because you instantiate it without a parent

#

and the RectTransform gets sad

willow scroll
#

I don't see how it's different from the Instantiate method, since they probably work similarly

wintry quarry
#

You might not see it, but it is different

#

I'm speaking from experience here

zenith cypress
#

Without a parent it gets created where the prefab is, so it can just be "somewhere". Plus without being under a canvas, it won't even render. Then if you parent after that, it can still be in the void somewhere and you still can't see it.

polar acorn
willow scroll
polar acorn
# willow scroll Why would it mess the layout?

Because it will set things like .position after the rect transform has been created, which will break the objects anchors and potentially cause it to have completely inaccurate values.

Setting the parent in Instantiate sets the position first, then the rect transform initializes and converts those values into rect space

zenith cypress
#

Not possibly, you will. Or its data will just be wrong. Instantiating with a parent already handles all that for you.

willow scroll
#

It may cause a bit more issues when moving the object from the world to UI, space, but if it's already inside of the same Canvas, there shouldn't be any issues

polar acorn
willow scroll
#

And, surely, if at some point the object's parent is supposed to be reassigned, you shouldn't reinstantiate it, additionally, given the instance has already been modified

polar acorn
#

You can fix it after calling SetParent by modifying the text transform, but at that point you might as well just Instantiate it directly as a child so the prefabs default values can be used.

If you open a prefab of a UI element, you can even see a phantom "canvas" parent that the prefab just assumes will be there when you spawn it

quaint flicker
#

This is a little vague, but I have a robot arm, with a couple 2 bone IK's on it, and a scripted controllable target, so I can basically direct where the arm goes. But if I build my level geometry around the arm and want to use it to move objects around the arm and the attached objects clip through the level geometry. (the "carried" objects are set to kinematic while they're parented to the arm). How should I fix it? (I basically have the same "problem", but less noticable, when my player character carries objects: they're parented and set to kinematic, so a carried box is freely clipping through the level and other objects)

silk night
#

should stop the arm from moving further if your box or whatever hits an obstacle

quaint flicker
rich adder
silk night
#

otherwise you can just change the .velocity for immediate direction change

#

otherwise you can counteract the described effect by first applying a force in the opposite direction of your movement with like 80% of power needed stop it and then apply the new direction, it doesnt break out as much tne

vestal adder
#

i dont think fixing a faulty movement system by adding an opposite fault is a good idea

#

am i understanding it wrong

queen adder
#

wussgood my fellow newbies

#

(idk if im the only one thats new to coding)

rich adder
#

probably not

queen adder
#

thats great lmao

#

also, this might sound like a weird question. But how do you guys get the hang of the C# structures within unity? I do understand the basics and the most important algorithms within C# but i never used those things within a project such as unity.

steep rose
#

structs? (replying to him)

rich adder
#

everything is the same , all the C# concepts are the same

queen adder
#

idk how to define it

rich adder
#

syntax never changes

steep rose
#

you just write with C# syntax

rich adder
#

all you have is Unity Specific classes / functions which is the API. If you can read any c# api you can read unity

#

for other specific unity concepts like GameObjects and their Monobehavior look up the manual or docs. Also check pins in this channel they have good mix of both

drifting geode
#

Hi I am making a grid Inventory and I am trying to place the object to the nearest grid where the mouse is but only the x coordinate is work the y is not working
https://hatebin.com/qlmyrnowfq

noble lark
#

And the ForceMode should still be fine as VelocityChange I'm guessing when applying the opposite force

sweet brook
#

heyy, i don't know anything about coding, but does someone have a good tutorial on how to make text appear after clicking an object? like if I click on an item make a text box appear with some info

steep rose
eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

sweet brook
steep rose
#

you will get used to it if you practice enough

rich adder
#

there are lot of things going on in those images

#

interfaces?

#

the example shown is telling you what its doing more or less, if you want multiple classes to have the same function, for example Damage. You just implement that interface

#

Now you can just look for IAttackable and not care if its a player or enemy cause they have the same function , each handles it their own way, hence "Implements interface" term is used, you are forced to use the method if the class implements the interface

#

you outta look this stuff up tbh

timber comet
#

Since they did not responded in #archived-networking (I waited a few days before asking here) I’m asking here: So i have a problem with my project: Basically when i spawn ONLY the host no warnings appears in the console, but when i try to spawn another player, it gives me continues warning about the rigidbody being kinematic (which it isn't in both rigidbodys), here my script for movement, for reference: https://paste.ofcode.org/pM6H2nvu8P9gzTxERxPhy5

rich adder
timber comet
rich adder
#

Client objects turn kinematic, the server handles all the simulations

timber comet
rich adder
#

no

#

did you spawn the Client with a connected Host?

timber comet
#

Yes

#

The host gives no warnings

#

Only when spawning the client in (with the host)

#

The player prefabs is a network object and has a network rigidbody (and a network transform), and almost all the scripts for the player are network behaviours

rich adder
#

probably trying to do client auth movement rn and its likely causing issue

timber comet
rich adder
#

haven't used rb movement on netcode yet so not something I can verify 100 rn. Thats why the netcode server pinned in #archived-networking is a better spot

timber comet
#

The client can move

#

It just gives me warnings

rich adder
timber comet
timber comet
rich adder
#

what package ?