#💻┃code-beginner

1 messages · Page 684 of 1

pallid nymph
#

A bit late to the discussion, but I feel having both an SO and a prefab (multiple of each) kinda defeats the purpose. At that point you can just have the prefabs and prefab variants. 🤷‍♂️

frosty hound
#

Unity has !Learn you can use as a starting point.

eternal falconBOT
#

:teacher: Unity Learn ↗

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

lapis parrot
#

can someone send me the link to the thing where you can copy and paste your code onto

eternal falconBOT
lapis parrot
#

tyty

frail hawk
#

you would have to use OnTriggerStay in this case or use a boolean as trigger

#

something like inRange true OnTriggerEnter and !inRange OnTriggerExit

sharp bloom
lapis parrot
#

booleans

naive pawn
#

it's not a unity thing

frail hawk
#

booleans can be true or false, in yourcase you simply declare the boolean at very top so it is reachable from the OnTriggerEnter and OnTriggerExit

naive pawn
#

it's a general programming thing

lapis parrot
#

im confused on how'd i'd implement that

frail hawk
#

you will have to learn some c# mate

#

nothing to worry about, we all had to do it, you can do it too

lapis parrot
#

true true

acoustic belfry
#

hey, i dont know why my enemies after i turned them into StateMachines walk backwards and they display their shooting animation instead of patrol animation, i specify the StateMachine thing cuz this means the external functions work well

https://paste.ofcode.org/tCf4yV5VQReBjB7TkvbKt6

rocky canyon
#

are you in the correct states? have u debugged and tested with validation?

acoustic belfry
#

i mean, it would be weird if it mixed states but i will try it now

rocky canyon
#

in mortemtrooperChase() ur always calling dispararmortem()) and playing "mortemrifleshooting" even when enemy is chasing and not in firing range

acoustic belfry
#

huh? im?

#

ou

rocky canyon
#

and ur sight logic may just be backwards as wel

acoustic belfry
#

aaaa, chase

#

but thats not the issue

acoustic belfry
acoustic belfry
#

is a gameplay issue not a coding issue, i will think of something better later

#

the issue is when patrols

rocky canyon
#

u said they walkin backwards

#

just lookin thru for a reason

acoustic belfry
#

i mean, they walk as they intend, but when they walk, their object size is made negative, for flip them whole

the issue, now flips them whole when dont need to

rocky canyon
#

i think its just a logic problem.. not really a code issue

acoustic belfry
#
    {
        if (detectoValeria == false)
        {
            contador -= Time.deltaTime;
            if (contador <= 0)
            {
                contador = tiempoParaCambiar;
                moverDerecha = !moverDerecha;
            }
            if (moverDerecha)
            {
                mortemRb.linearVelocity = new Vector2(speed, mortemRb.linearVelocity.y);
                transform.localScale = new Vector3(1, 1, 0);
            }
            if (!moverDerecha)
            {
                mortemRb.linearVelocity = new Vector2(-speed, mortemRb.linearVelocity.y);
                transform.localScale = new Vector3(-1, 1, 0);
            }
        }
    }```
rocky canyon
#

the patrol method plays riflepartrol.. but ur mortemtropper chase also plays rifleshooting always even when too far to shoot

acoustic belfry
#

o no it always shoots

rocky canyon
#

so if u ever accidently land in Chase while far they'll still shoot

acoustic belfry
#

the far thing is for check if should chase or stay in place

rocky canyon
#

yea for the walkin backwards thing i would guess u flip based on the player position and not its current movement

#

soo u get like a moon-walkin trooper

acoustic belfry
#

yep

rocky canyon
#

u could flip by velocity

acoustic belfry
#

velocity?

rocky canyon
#
void flipByVelocity(Rigidbody2D rb)
{
    if (rb.velocity.x > 0.01f)
        transform.localScale = new Vector3(1, 1, 1);
    else if (rb.velocity.x < -0.01f)
        transform.localScale = new Vector3(-1, 1, 1);
}```
#

ya the direction ur enemy is moving basically

#

if X velocity is positive ur moving ->

#

if X velocity is negative ur moving <-

acoustic belfry
#

o h

rocky canyon
#

also debug ur states while working

#

it'll help ... maybe even a little overlay TextMeshPro

#

Debug.Log(currentState); textMeshPro.text = currentState.ToString();

acoustic belfry
#

I discovered the issue, wasn't coding, i forgot that i tried to use the animator for the scripts, instead of just put the play

now i check the transitions made this issue

#

well, thanks anyways, atleast now i can debug my states, and i know how to flip better :3

rocky canyon
#

yup

acoustic belfry
rocky canyon
#

yea same thing

#

if ur using unity6+ its linearVel

#

if its older its vel

waxen adder
rich adder
gleaming haven
#
using UnityEngine;

public class Gravity : MonoBehaviour
{
    [SerializeField] private CharacterController controller;    //reference to CharacterController component of FPS_Controller
    [SerializeField] private float gravity = -9.81f;            //gravity in m/s²
    public float downwardVelocity = 0f;                         //downward velocity gradually increases during free fall

    // Update is called once per frame
    void Update()
    {
        //reset downwardVelocity if player is on the ground 
        if(controller.isGrounded && downwardVelocity < 0){
            downwardVelocity = 0f;
        } else {
            //increase downward velocity using the gravity value
            downwardVelocity = downwardVelocity + gravity * Time.deltaTime;
        }

        //create vector from downward velocity along Y axis
        Vector3 gravityVector = new Vector3(0f, downwardVelocity, 0f);

        //apply gravity vector to the player
        controller.Move(gravityVector * Time.deltaTime);
    }
}

does anybody know a quick fix to why the downwardVelocity still increases while standing on the ground? it should only increase when the player is mid air, but I cant get it to work

waxen adder
#

The first thing I can say is double check your logic surrounding controller.isGrounded. Could add some debug.logs to see what state it's in as well

gleaming haven
#

i tried that, it seems to only spit out debug logs when i move the character, so it appears to not update when the character is standing still

waxen adder
#

Where'd you put the logs?

gleaming haven
#

into the first "if"

waxen adder
#

Put it out in update land

#

So like:

void Update()
{
Debug.Log("Is grounded value: " + controller.isGrounded);
...stuff
}
gleaming haven
#

oh yeah wait

#

it says false even if im on the ground, thats odd

#

maybe it's wrong to check isGrounded on an empty object

#

because my controller is an emptyobject with the charactercontroller component

waxen adder
#

Personally I haven't messed with physics/jumping logic, so I can't say what's the best there, but yeah, from what it seems there's at least something wrong with the logic around isGrounded

gleaming haven
#

ill look into it, ty

wintry quarry
#

CharacterController.isGrounded is notoriously bad

#

almost everyone uses their own separate grounded check implementation

#

usualy with raycast or capsulecast

magic knoll
#

Hey guys, I wasn't really regarding on my console during my last modifications, and I have those errors that spawns on my game start.
I think i checked all my prefab serialize objects, and everything seems clear.
Do you have any suggestion to help localize this kind of errors ?

#

I tried to remove almost all prefab ref of my scene, but still occurs

#

And it doesn't prevent the game to run

rocky canyon
#

looks like Editor issues.. and not anything you've done..

#

u can try restarting the project/ editor/ perhaps the PC

#

can also try deleting the Library folder w/ the project closed and re-open it to allow Unity to rebuild its Library.. (sometimes that sorts out unknown errors)

magic knoll
#

Damn

#

It's been 30mn i'm looking every single object of my game xD

rocky canyon
#

lol oof

#

check out the errors

#

anything UnityEditor. blabla is editor stuff

naive pawn
rocky canyon
#

if u dont have editor scripts.. then its most likely a unity thing and not a you thing

magic knoll
#

Yeah, I saw that but i don't know, i thought i made some really terrible script that was breaking something ^^

rocky canyon
#

could also just be a bugged out window..

#

reset the Layout as well

magic knoll
#

Just restarted the editor and it fixed 😄

rocky canyon
magic knoll
#

Noted!

harsh haven
#

Hi, need some basic physics help:

Basically, making a simple basketball game.
I am implementing jumping and picking up the ball, and to do jumping i had to use rigidbody and allow the character to be affected by forces. Both jumping and ball pickup work fine, but not together, as

The ball while dribbling makes contact with the player, and so pushes the player in weird directions and messes up movement. I fixed this by excluding the ball layer from the player's rigidbody. However, if I exclude this layer, the player's ontrigger component no longer recognizes the ball when the two make contact and the ball needs to be picked up after shooting. How can I allow the player and ball to register collisions (so ball pickup can happen), but the physics of the two don't affect eachother when in contact?

rocky canyon
#

well sounds like ur onto a solution already

#

u can change layers, and rigidbody settings @ runtime..

#

settings that allow pickup -> then once picked up -> change settings that allow dribbling

harsh haven
#

When ball is dribbling, exclude the ball layer from rigidbody

#

When the ball needs to be picked up, include it

#

ok yea true lol i just didn't know if this was the best solution, cause like

#

since im a beginner i dont wanna bring up bad habits or work around solutions in weird ways

#

thought there was maybe a more direct way to fix it universally

rocky canyon
#

there probably is.. but it'd be more convoluted and more complex than using the settings/ layers/ and tickboxes they already have

#

or u could have a pickup ball thats different than ur play ball

harsh haven
#

oh yea thats an interesting idea too

rocky canyon
#

thats how most games actually do pickup objects in general

#

theres a pickup thats basically a trigger
when u pick it up.. u despawn (destroy) /disable that object
and spawn in the real object that pickup represent

lapis parrot
rocky canyon
#

dont poll for inputs in trigger function

#

that only runs X amount of times / second.. UNLESS u hit it EXACTLY when that function gets called its pointless

#

instead use a boolean or something to toggle when and when not to poll for input

lapis parrot
#

wait

#

i kinda understand what you mean

rocky canyon
# lapis parrot i kinda understand what you mean
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (isInTrigger)
            {
                Debug.Log("Space key was pressed and we're in the trigger");
            }
            else
            {
                Debug.Log("Space key was pressed but we're not in the trigger");
            }
        }
    }

    void OnTriggerEnter(Collider other)
    {
        isInTrigger = true;
    }

    void OnTriggerExit(Collider other)
    {
        isInTrigger = false;
    }```
#

does this clear things up?

#
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space) && isInTrigger)
        Debug.Log("Space pressed & in trigger");
}``` or combine the two conditions...
#

point being that Update() runs every frame... so when u press the input it gets grabbed.. regardless

#

and then u check also if ur in the trigger (if ur not it gets ignored) and let the code run

#

this doesnt mean anything in ur code...
its set to true.. and it'll always be true b/c u dont change it anywhere..

isInRange can be exactly what i used up above ^

if u enter trigger set it to true..
when exit trigger set it to false..

#

then do ur input like regularly in Update().. and check that boolean

boreal night
lapis parrot
rocky canyon
#

nah, i wouldn't say all that..

#

but its a common way to do inputs 'n triggers

spiral night
#

Hi, I'm brand new to unity and coding. I'm just starting the book that advertised this group.

I'm literally a complete noob, but I've realised that visual studio for mac used in the book isn't supported anymore so I have to use visual studio code. I feel quite dumb saying this but I'm finding it quite difficult to follow along with the instructions in the book because visual studio code doesn't have the start method I'm told to put the debug.logs inside of.

Does anyone have any advice? Should I just copy the diagram in the book into visual studio code?

eternal falconBOT
polar acorn
#

But the Start method is not related to your IDE

rocky canyon
#

it surely does

polar acorn
#

It'll be in the default script template no matter what IDE you're using

spiral night
#

Thank you, I will try configure this.

rocky canyon
#

you'll also want a few extensions to help out.. the c# devkit.. unity/ unity snippets

spiral night
#

Thank you very much! Have you completed the book at this stage?

rocky canyon
#

ive been using unity for 5 years now

lapis parrot
rocky canyon
#

well, did you declare a boolean to use?

rocky canyon
#

they dont just exist... u have to declare a boolean

#

and use that to set true and false in ur trigger functions

spiral night
rocky canyon
#
    public class TriggerCheck : MonoBehaviour
    {
        public KeyCode interactKey = KeyCode.Space;

        private bool isInTrigger;

        void Update()
        { ....```
i didn't post the full script.. (just an example)
rocky canyon
lapis parrot
#

oh i see i see

#

neuron activation here

rocky canyon
#

gotta think outside that box a bit

ivory bobcat
spiral night
#

oh okay I thought I was following the book but I must have made a mistake. I will go back and redo this properly. thank you very much

rocky canyon
#

pro-tip rename the script during creation and the class name will match in the script..
avoiding problems like forgetting to rename the class

spiral night
#

oh yes I got that in my notes 😂 I think my problem was I went into scripting and chose empty c# script instead of monobehaviour

lapis parrot
rocky canyon
#

then ur trigger must not be setting it to "true"

lapis parrot
#
 private void OnTriggerEnter2D(Collider2D other) //Player entering item range
    {
        bool isInRange = true;
    }
ivory bobcat
#

Are you also setting it to false anywhere? You declared a local variable there, in that method, and assigned it the value true.

polar acorn
#

When the function ends, that variable ceases to exist

lapis parrot
#

oh shoot

#

no private

rocky canyon
#
   void OnTriggerEnter(Collider other)
    {
        Debug.Log($"We collided with: {other.name}");

        if (other.CompareTag("Player"))
        {
            Debug.Log("We tested and collided with the player!");
            isInTrigger = true;
        }
    }```
#

the boolean needs to be declared at the top

#

outside the functions

#

that way the entire class can use it

#

^ and if u put [SerializeField] in front of it.. it'll expose it in the inspector.. that way u can physically watch it change during testing

lapis parrot
rocky canyon
#

well ya but ur not assigning the bool at the top

#

ur creating a NEW one... in the triggers..

#

dont do that

polar acorn
#

Don't declare new variables.

#

Assign the one you already have

rocky canyon
#

just set the isInRange boolean you already have

ivory bobcat
#

You'd only usually see the type when declaring a new variable. You'd just use the variable name when wanting to access a variable.

rocky canyon
#
public class PickUpScript : MonoBehaviour
{
    public GameObject StartSwordPickup;
    public GameObject StartSword;

    public KeyCode interactKey = KeyCode.E;

    private bool isInRange;

    void Update()
    {
        if (Input.GetKeyDown(interactKey))
        {
            if (isInRange)
            {
                Debug.Log("Picked Up!");
                StartSwordPickup.SetActive(false);
                StartSword.SetActive(true);
            }
            else
            {
                Debug.Log("You're not in range!");
            }
        }
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        isInRange = true; // Correct: modifying the class field
    }

    void OnTriggerExit2D(Collider2D other)
    {
        isInRange = false; // Correct: modifying the class field
    }
}``` this is what u *should* be doing..
#

in this situation ^ ur declaring (1) boolean to use within the ENTIRE class

#

its the same one u set in the trigger functions.. and the same one u check in ur update conditionals

#

anywho.. that should set you up for success.. my freebies have been exhausted for today 😈

lapis parrot
#

oh my God it's because i kept on putting "bool" behind them

teal viper
#

It's called variable declaration. You're basically saying "there's gonna be a new variable with this name here"

polar acorn
ivory bobcat
#

Whereas without the type, you're saying that you've got a variable already by a particular name and are wanting to do something with it.

rocky canyon
#

so anywhere outside of MyFunction() thisFunctionsBool can not be accessed

#

you'll sometimes want to have variables that the function may need to execute w/e it is that its trying to do.. but those variables aren't needed anywhere else..

#

like for example if u had a function that did alot of math and spits out a number
you may need to use variables to temporarily store numbers to calculate with later on in the funciton
but those variables aren't needed elsewhere

outer coral
#

kind of odd question but:

If i have a virtual method that I am overriding and in the subclass implementation I use the base.MyFunction(); call is there a way i can return out of both from inside the base method? For example I want to check a condition on every object that uses that class but I dont want to rewrite the check for them all I just want it to short circuit but since I have other implementation after the base call it would still run. Any way to do this without copy pasting

red rover
#

Just a sanity check, continue will continue in the closest loop, right? The z loop in this case?

for (int x = -4; x <= 3; x++)
{
    for (int y = -4; y <= 3; y++)
    {
        for (int z = -4; z <= 3; z++)
        {
            if (l > 0 && CheckGapRange(x, y, z)) { continue; }
        }
    }
}```
past yarrow
#

!code

eternal falconBOT
past yarrow
#

Hey,
I tried to optimize my GenerateOtherTiles() method to use nested loops instead of alot of if statements but for some reason it broke my game, reavealing all the tiles in the grid when I click on a tile and also not displaying the numbers on the the tiles when I click on a tile. Does anyone know why please ?

Here's the optimized code that I wrote for that method:

private void GenerateOtherTiles()
{
  for (var i = 0; i < GRID_WIDTH; i++) {
    for (var j = 0; j < GRID_HEIGHT; j++) {
      if (tiles[i,j].Value == -1) continue; // If it's a "Mine" tile, skip all the code below
      
      var minesAmount = 0;

      // Loop on every neighbour around the current "Tile"
      for (var h = -1; h <= 1; h++) {
          for (var v = -1; v <= 1; v++) {
              if (h == 0 && v == 0) continue; // This is ourselves, not a neighbour, so "continue"
              if (!IsInGrid(h, v)) continue;  // The coordinates "h,v" are outside the grid, so "continue"
              if (tiles[h, v].Value != -1) continue; // If the neighbour isn't a mine, "continue"

              minesAmount++; // It's a mine, so add 1 to "minesAmount"
          }
      }
      tiles[i, j].Value = minesAmount;
    }
  }
}

Here's the previous code that I backed up before doing that change : https://paste.mod.gg/tlzuqzajpsnu/0
All the rest of the code is the same in both 🙂

#

I think I know why 🤔 I forgot to add h and v to i and j 😬

#

Yup, that's the issue, thanks 👍 🙂

heady herald
#

hey yall, can anyone help me figure out how to make this code not freeze up unity? I think im doing a memory leak or underestimating how expensive this code is, but its freezing unity indefinitely and i do not want it do that

using System.Linq;
using TMPro;
using UnityEngine;

public class ClockScript : MonoBehaviour
{
    public TMP_Text ClockText;
    public int TicksTilNextUpdate = 150;
    public static OurUniversalClasses.OurDateFormat CurrentDateTime;

    private void Awake()
    {
        CurrentDateTime = new OurUniversalClasses.OurDateFormat();        
    }
    void Start()
    {
        ClockText = GetComponent<TextMeshProUGUI>();
    }
    void FixedUpdate()
    {
        
        if ( ((float)TicksTilNextUpdate)/25f % 1 == 0 && ClockText.text.ToList().Contains(":".ToCharArray()[0]))
        {
            //Debug.Log("yep");
            ClockText.text.Replace(":", " ");
        }
        else if(((float)TicksTilNextUpdate) / 25f % 1 == 0)
        {
            ClockText.text.Replace(" ", ":");
        }

        TicksTilNextUpdate--;
        if( TicksTilNextUpdate < 0 )
        {
            
            CurrentDateTime.AddSeconds(60);

        }
    }
#

tysm

#

what this is supposed to do is make a clock do that thing where the ":" blinks in and out

#

ideally it would do that every half second

sour fulcrum
#

Can't see anything in this that would freeze unity 🤔

heady herald
#

hm weird

sour fulcrum
#

by the way, string has a contains function directly

heady herald
#

im pretty sure its this script causing it but maybe i should do a more thorough check

sour fulcrum
#
if (text.Contains(':'))
heady herald
#

probably should have checked before doing that jank 😭

#

yeah it runs fine until i turn on the script

#

then immediately starts freezing

#

fixed update gets called 50 times a second by default right?

#

it takes a bit to start crashing so it feel memory leak to me but also idk what could even be leaking

#

these are all local varriables so they should get automatically dissmissed

sour fulcrum
#

Also hope you don't mind the feedback, but you don't need to do that check twice, you could just do

        if (((float)TicksTilNextUpdate) / 25f % 1 == 0)
        {
            if (ClockText.text.Contains(':')
                ClockText.text.Replace(":", " ");
            else
                ClockText.text.Replace(" ", ":");
        }

or

        if (((float)TicksTilNextUpdate) / 25f % 1 == 0)
        {
            (string,string) swap = ClockText.text.Contains(':') ? (":"," ") : (" ", ":");
            ClockText.text.Replace(swap.Item1, swap.Item2);
        }
heady herald
#

yeah fair

#

i was trying to avoid nesting but that 2nd option is much cleaner

sour fulcrum
heady herald
#

hm maybe

sour fulcrum
#

tbh could also just have two textmeshprougui's where one has it and the other doesnt

#

and flip their activity

heady herald
#

yeah maybe thats easier

#

the ticking works fine

#

when i comment out the if

#

which was kinda expected

#

nvm i lied to you

#

the editor frozen when i was typing

#

uh oh

#

should i just not be calling fixed update

sour fulcrum
#

no that should be very harmless

#

usually full freezing stems from either while loops or recursion

heady herald
#

yeah this is weird

#

commenting out the incrementing of TicksTilNextUpdate seems to work to stop crashes

#

but also

#

i really need that...

#

oh wait intresting

#

it only crashes when ticks hits 0

#

i think its a problem with my datetime function

#

yeah its just the datetime function which is broken apparently

#

okay yep its just sleep deprived function writing

#

ty for your help!

sour fulcrum
#

Glad you got it working 😄

lusty viper
#

Anyone know how to find the acceleration for an object given its mass and the strength of a force being applied to it? I tried doing just acceleration = mass / force, but I guess I'm not sure what units are being used because the resulting number didn't seem to line up at all with the actual change in magnitude of velocity over time

heady herald
#

what are you using this for?

#

dependin on your use case, you could just get acceleration by comparing velocity at two different times

#

calculate it as a change in veloctiry

#

unless you need to predict aceleration, its imo best to just compare two velocities and times

lusty viper
#

Yeah, that's what google says a lot haha. I'm using it to try to know the potential acceleration possible given you apply a certain force. Basically I've got a little spaceship guy and I want to have it accelerate towards a target, and at every tick, figure out whether it should be accelerating forwards or decelerating such that it reaches the target with velocity 0

heady herald
#

how set are you on using physics over translation?

#

might as well check

eternal needle
lusty viper
eternal needle
#

you also cant compare the results right away as addForce actually changes the velocity duing the physics loop, if you were doing that

heady herald
#

i see

lusty viper
#

I'll try that out, thanks!

eternal needle
lusty viper
#

Oh it was, mb

coarse stag
#

Can someone link me a good C# course, that shows every step piece by piece

cyan crescent
#

Hi, just started learning to code using c# in Unity to create a game. I'm still having a hard time understanding codes like functions and symbols (like the difference between (), {}, =, . and others) using visual studio. Are there any good tutorials to familiarize myself to basic code functions?
Currently using this tutorial as my first guide, very helpful but wanna know if there is anything more basic than this one. Thanks

https://youtu.be/XtQMytORBmM

sour fulcrum
#

the usage of those characters is very consistent so it's easy to pick up on when and where you'd use it based on the context

cyan crescent
visual linden
# cyan crescent Thank you for the recommendations, I was really excited when I was able to move ...

If you're new to programming entirely I'd recommend checking out something like Harvard's CS50: Introduction to Computer Science (https://youtu.be/LfaMVlDaQ24)
Learning programming through Unity can be a bit of a painstaking process since you're essentially learning two (three?) domains at once. Watching a few of the CS50 lectures and maybe a brief C# tutorial would probably get you writing code confidently much quicker.

sour fulcrum
young niche
#

hey im trying to make an elevator in my game, however i use a character controller component, and when im in the elevator my character is like boucing when it goes down. Im guessing this is a gravity issue, but im not sure how to fix it since i dont want to use a rigidbody. Somebody know any easy solutions to this?

naive pawn
#

sounds like your elevator is going faster than gravity?

young niche
#

yeah, i think so, but i slowed it down a bunch so now it goes really slow, but i still bounce. Is there a way to like "glue" me to the floor of the elevator?

grizzled crag
#

what do you mean by bouncing

young niche
#

or right now i calculated that my elevator is going 1.5 units per second, while gravity is 9.81 units per second. So gravity sohuld be able to pull me down, but maybe since the elvator is a "steady" constant movement downward. While gravity accelerates velocity from 0 upward. Therefore it will bounce, however im not sure how to fix it

teal viper
grizzled crag
#

minus the rb of course

#

since you're using character controller

young niche
#

im not using a rigidbody, since i have my character controller

teal viper
#

Disable the character controller then.

young niche
#

yeah i tried to parent but it didnt really help

#

maybe, but i would like my character to still move in the future if im standing on objects that animate downward

grizzled crag
#

mmmm okay what if

#

make a script that forces the character to copy the y level of the elevator + an offset

#

and turn off the character controller's gravity

#

this should still allow you to move on the xz plane

#

while following the elevator's y position

teal viper
sharp bloom
# cyan crescent Hi, just started learning to code using c# in Unity to create a game. I'm still ...

Just keep coding. They will become muscle memory.
My favourite C# resource is https://www.geeksforgeeks.org/c-sharp/csharp-programming-language/ , nice clean examples and explanations for all the basic stuff

sharp bloom
#

What's the best approach of implementing "generic" animations like reload, take aim, shoot across multiple types of weapon?

#

AnimatorOverrideController? I don't quite get how to use it.

static breach
#

uiCanvas = canvasObj.AddComponent<Canvas>();
why does my game, even when i have this in my code always creates my generated ui elements inside an already existing canvas? i want a new canvas to be created

#

oh i might found the issue

#
        if (uiCanvas == null)
        {
            Debug.Log($"Creating new Canvas for client {NetworkManager.Singleton.LocalClientId}");
            GameObject canvasObj = new GameObject($"MinimapCanvas_Client_{NetworkManager.Singleton.LocalClientId}");
            uiCanvas = canvasObj.AddComponent<Canvas>();
            uiCanvas.renderMode = RenderMode.ScreenSpaceOverlay;
            canvasObj.AddComponent<CanvasScaler>();
            canvasObj.AddComponent<GraphicRaycaster>();
        }
        else
        {
            Debug.Log($"Using existing Canvas for client {NetworkManager.Singleton.LocalClientId}");
        }
        ```
how do i tell him what canvas to use?
queen adder
#

I have a problem that when I added a code to make my character dash It stopped moving left and right
here's the script:
https://gist.github.com/bielo1656/02920ebd582adf83941b6da1f49b8f04
I tried to move the "body.linearVelocity = new Vector2(horizontalInput* speed, body.linearVelocity.y);" line to a FixedUpdate method but it didnt fix it
Also the player settings in the editor

Gist

PlayerMovement. GitHub Gist: instantly share code, notes, and snippets.

static breach
#

fixed my problem

naive pawn
queen adder
#

OOOH MY GOD

#

I hate when I search for hours for an error just for me that I've done something stupid

naive pawn
#

sounds like you should learn debugging then

#

just putting Debug.Logs in the right place to see what's going on

queen adder
knotty night
#

Debugging is really just you asking your computer, "wth is wrong here?" When your code isn’t working

its about

Figuring out what’s messed up
Understanding why it's happening
Fixing it so it actually works

Sometimes it’s just a stupid typo, like forgetting the semi colon (;), and other times it’s a tricky logic issue. just be patient, and ready to do some Googling, theres nothing wrong about it\

burnt vapor
#

We can't explain debugging any better than those pages do.

knotty night
burnt vapor
#

Been here for a long time

knotty night
#

oh, this is the first time i opened the page

burnt vapor
#

It is referenced very often

knotty night
#

i see, i guess i have a documentation now

sharp bloom
#

Looked into factory pattern, this script does basically that you suggested.

public class ProjectileFactory
{
    public GameObject RealizeProjectile(SO_ProjectileConfig config)
    {
        if (config.itemPrefab == null)
        {
            Debug.Log("Projectile has no prefab.");
            return null;
        }

        GameObject newObject = config.itemPrefab;
        GameObject realObject = Object.Instantiate(newObject);
        realObject.GetComponent<IItem>().Initialize(config);
        return realObject;
    }
}

Now I don't have to make both the prefab and the scriptable object manually, just need to have the generic projectile script on the prefab. This works for me 👍

final kestrel
#

!ide

eternal falconBOT
heady herald
#

hey yall, im running into some problems where InputField.isFocused always returns false

#

I was under the impression that it would be true when the InputField is being edited and false when its not

#

but that doesn't seem to be happening

#
    public void Update()
    {
        bool anyEnter = Input.GetKeyDown(KeyCode.KeypadEnter) || Input.GetKeyDown(KeyCode.Return);
        if (anyEnter && inputField.isFocused == true)
        {
            Debug.Log("hit");
            Lines.Add("");
            inputField.text = "";
        }

        //stupidly expensive. its ok
        Lines[^1] = "> " + inputField.text.Replace("\u2588", "");
        ReloadText();
    }
#

huh

#

my code for referance

slender nymph
#

why manually poll for enter+focus when you can just subscribe to its onSubmit event instead?

heady herald
#

ill check that out, ty

gaunt solstice
#

Hello, I need help with a 2d platformer I'm making. I want to have a mechanic similar to mario or sonic where the player can jump on an enemy, and when they do they bounce off the enemy a little. I was able to get the bounce working fine but I want to make it so the height of their bounce is dependant on how fast they're falling and that doesn't seem to be working. Here's the code I have so far

    {
        float fallingSpeed = Mathf.Abs(rb.velocity.y);
        float bounceForce = fallingSpeed * bounceMulti;

        rb.velocity = new Vector2(rb.velocity.x, bounceForce);
    }```
rich adder
gaunt solstice
#

so is it cause when the collision happens the falling speed decreases?

rich adder
gaunt solstice
#

so how do i log it before the collision happens

delicate zinc
#

is there any way to make ontriggerenter detect a boxcollider of a child instead of just every boxcollider on the object

rich adder
delicate zinc
#

i have it set up where the player hitbox is a seperate object thats animated when the player attacks, but since the player spins when they attack, the player hitbox sometimes clips into the enemy and activates a hit anyway

rich adder
#

probably using Layers / Collider filtering

delicate zinc
#

is there any way to get the hitbox specifically from this

rich adder
delicate zinc
#

other is checking for the enemy so idk how to check for my hitbox

rich adder
#

you would need a reference to it but don't think that will do what you want

#

you want that to ignore something why not change the Layers filtering or am I not understanding what ur issue was

delicate zinc
#

wait a sec lemme try find a better way to explain it lol

#

the enemy has a script that checks for playerhitbox when it takes damage (screenshot 2), and the player hitbox has that, but the script that i put on the player to apply recoil and knockback still goes off sometimes without dealing damage, since the players hitbox clips into the enemy (screenshot 3)

rich adder
delicate zinc
#

do what

rich adder
#

recoil and knockback still goes off sometimes without dealing damage, since the players hitbox clips into the enemy

delicate zinc
#

lemme get a video

#

at least i think the player hitbox is clipping into the enemy since idk what else would be causing it

#

i do it at like 0:09

rich adder
delicate zinc
#

no its meant to hit the enemy and deal damage but in the video i somehow knockback without the red trigger hitting it

#

so the enemy doesnt take damage

lusty viper
#

What's causing the knockback? Is it a separate collider?

delicate zinc
#

i found a way to consistently trigger it if i run into the enemy near the end of the animation

delicate zinc
rich adder
#

you have different triggers on the player ?

delicate zinc
delicate zinc
rich adder
#

cause that knockback only waits for Triggers

lusty viper
#

Sounds like you need the script that causes the knockback to be on a different nested gameobject with the red collider so that onTriggerEnter would only trigger for that one

delicate zinc
#

ouh oka

#

ill try that

rich adder
#

does the enemy have regular collider or trigger?

lusty viper
#

That's my first guess anyways, probably other solutions

delicate zinc
rich adder
#

a rigidbody also ?

delicate zinc
#

yeah

rich adder
#

could be colliders going into eachother rather then knockback itself, you could try to comment out the knockback part or put a log to see if thats the one causing it

delicate zinc
#

it is the knockback tho since it causes the game to slow down and play the sound effect

lusty viper
#

I would say one gameobject per thing that colliders are supposed to do is generally a good idea but I'm not an expert idk

delicate zinc
#

omg that fixed it

#

tyyyy

gentle merlin
#

iam getting this errer

InvalidOperationException: Nullable object must have a value.
System.Nullable`1[T].get_Value () (at <d6e80b37d98246a5859a00c653f9fdf3>:0)
BotAI.MakeMove () (at Assets/Scripts/BotAI.cs:115)
BotAI.TryMakeBotMove () (at Assets/Scripts/BotAI.cs:619)
BotAI.Update () (at Assets/Scripts/BotAI.cs:623)

and its coming from var bp = best.Value; here

https://paste.mod.gg/tvwudnkmyxpe/0

#

and i canno't for the life of me trace it down

naive pawn
#

it's telling you where the source is

#

best doesn't have a value, it's being used on line 115

gentle merlin
#

ik that bp is returning as 0, but i can't find where it becomes 0

naive pawn
#

that's not what it means, no

gentle merlin
polar acorn
naive pawn
#

also have p as Chessman instead of GameObject

gentle merlin
#

not a single one goes off

naive pawn
gentle merlin
naive pawn
#

(why do you have the dMax loop anyways, it doesn't do anything)

gentle merlin
#

this shit is empty

#

i was trying to trace each variable back to its soucre when i found this, let me fill it in and see

gentle merlin
#

looking back that section of code has always beem empty, and it had been working until now so i don't think thats the error

torn dragon
#

guys am new to unity and this scene looks fine here but

torn dragon
#

i cannot see anythibng when i

#

switch to this

polar acorn
torn dragon
polar acorn
torn dragon
#

how much should this value be

polar acorn
#

Scroll wheel while moving to adjust

#

But from this view, select your camera and see what's in its view

torn dragon
polar acorn
torn dragon
naive pawn
#

press F to focus

torn dragon
naive pawn
#

you're currently either way too zoomed in or out

torn dragon
#

why is my main camera moving

#

the z coordinates are changing constantly

#

its nowhere near the main thing

#

player

#

and its going further away in z axis

polar acorn
#

And yes, that does indeed seem very far away

torn dragon
polar acorn
#

Check your code

torn dragon
#

i don't have a code for camera though

polar acorn
#

But you have cinemachine that is presumably following something, and probably code that moves that thing

torn dragon
#

this is fine ig

#

so this player model is supposed to move in a linear path but its not

acoustic belfry
#

what diferences, animator.play and animator.crossfade have?

for direct logic usement of animation wich one's better?

kindred iron
#

u can see the difference between them in yt ig

torn dragon
#

We're going to add parallax to our 2D scene's background layers, then make it endlessly scroll!
This is a complete tutorial - from adding player, setting up the camera - to a beautifully scrolling background! Basically make a whole endless runner / side scroller in 7 minutes :o

FREE Player Package: https://www.patreon.com/posts/102090173
FULL P...

▶ Play video
#

0:45

#

the player model moves on x axis

#

she has the asset and i imported it

kindred iron
torn dragon
kindred iron
acoustic belfry
naive pawn
#

@kindred iron @torn dragon we'd rather you discuss here, fyi
going to private chats defeats the purpose of having a community server

naive pawn
#

just use Play for simplicity

kindred iron
#

and thats the purpose

#

and

#

we dont discuse in private

#

but instead he streams in private and he shows me the problem

#

its better like that

acoustic belfry
naive pawn
naive pawn
# kindred iron and thats the purpose

the purpose of a community server is to have multiple people available to help any given person - multiple people able to see potential issues, perhaps point out things that will be an issue in the future as well

with private help, DMs, calls or streams, that's completely lost - and if that one helper happens to become unavailable or is unable to help, it then becomes the asker's problem to ask everything all over again for someone else

kindred iron
#

and i increase my english too when i speak

naive pawn
#

additionally, with a public discussion, other people in the chat can benefit from the conversation as well, and other members can check answers, and moderators can do their job

kindred iron
#

so i prefer talking tbh

naive pawn
#

ok, live with the conscience that you're harming other people by taking the "easy" option i guess

idk why you'd say it's easier to handle in VC either tbh, i find it wayyyy easier when stuff is laid out in text or images
video and especially audio is a pain to check through when trying to find issues

#

being able to communicate issues in text is a skill that definitely needs way more practice than talking

#

these things are standardized for a reason shrugsinjapanese

gentle merlin
#

is there a reason this code is nto stopping for friedly pieces? (gave up on the other bot so iam using my second bot i had made but this pesky issue i the only thing it as rn)

public void LineMovePlate(int xIncrement, int yIncrement)
    {
        Game sc = controller.GetComponent<Game>();

        int x = xBoard + xIncrement;
        int y = yBoard + yIncrement;

        while (sc.PositionOnBoard(x, y))
        {
            GameObject piece = sc.GetPosition(x, y);

            if (piece == null)
            {
                MovePlateSpawn(x, y);
            }
            else
            {
                if (piece.GetComponent<Chessman>().player != player)
                {
                    MovePlateAttackSpawn(x, y);
                }
                // Stop for either friendly or enemy piece
                break;
            }

            x += xIncrement;
            y += yIncrement;
        }
    }
gentle merlin
#

I have one piece thats like the queen in chess, and it uses this method to move. So far tho its first move in the game its to jump over its friends and eat my pawn

naive pawn
acoustic belfry
#

what is hashing?

#

Someone knows a way to check the quality of a script? Or how re-organize it?

Cuz im trying to enchance my player's script but i dont know how

naive pawn
#

"quality" is a quite subjective and, well, qualitative

pallid nymph
#

You can always ask ChatGPT 😅

#

I'm sorry, I couldn't help it. You probably shouldn't do that.

naive pawn
#

the main things i'd look for at a beginner level would probably be

  • repeated code or things that could be generalized with math
  • numbered variables
  • indirection/magic strings/magic numbers
naive pawn
pallid nymph
#

I should try it as well, I'm sure it would be fun 😄

naive pawn
brave robin
#

"Hi, I can totally help you with your Unity code! First off, it is wasteful to cache your GetComponent calls in Start, you should instead call GetComponent in Update..." - ChatGPT

acoustic belfry
#

... sorry

polar acorn
#

It's not really a quantifiable thing

acoustic belfry
#

atleast readable

#

im trying to modify and check my player's script, yet...i dont even understand what i did

#

or i should just follow the joke fused with advise
"If it works, leave it alone"

polar acorn
#

You just kind of decide how much you hate yourself looking at the code. If it's a little bit, you're probably fine. If it's a lot, you should fix it. If it's not at all, then you probably don't yet know why you should hate it and should probably take another look

acoustic belfry
#

i hate myself

polar acorn
#

Right, but like the normal programmer amount

#

or more so

acoustic belfry
#

with or without the code

#

but in this case

#

with the code

acoustic belfry
#

but now returning to seriousness, well

#

i dont...understand it, and i feel like i should do it

acoustic belfry
#

like im not made for this yet i want to

#

Hiccup but for coding

gentle merlin
# naive pawn try debugging some stuff, check if `piece` is what you expect it to be in each g...

i checked and yeah all the pieces are where they are supposed to be, it says it breaks out of the loop when it encounters a friedly piece but then dosen't? its checks board positions not in the assigned increments as well, and then jumps to a position which it previously indicated there was a friedly piece in that line and that it had broken out of the loop.

 public void LineMovePlate(int xIncrement, int yIncrement)
    {
        Game sc = controller.GetComponent<Game>();

        int x = xBoard + xIncrement;
        int y = yBoard + yIncrement;

        while (sc.PositionOnBoard(x, y))
        {
            GameObject piece = sc.GetPosition(x, y);
            print($"Checking position ({x},{y}): piece = {(piece == null ? "null" : piece.name)}");

            if (piece == null)
            {
                MovePlateSpawn(x, y);
                print($"MovePlateSpawn at position: ({x}, {y})");

            }
            else
            {
                if (piece.GetComponent<Chessman>().player != player)
                {
                    MovePlateAttackSpawn(x, y);
                }
                else
                {
                    Debug.Log($"Blocked by friendly piece at ({x},{y}), stopping move generation");
                }
                Debug.Log("Breaking the while loop now.");
                break;
            }

            x += xIncrement;
            y += yIncrement;
        }
    }
#

its not checking the board like a queen, its literly just scanning the whole board

naive pawn
#

are you calling LineMovePlate multiple times? the logs might be confusing if you are

gentle merlin
split plover
#

Quick question, if a coroutine is in an if statement will it still fully go through the full coroutine if the if statement isn't active after the coroutine starts

naive pawn
split plover
naive pawn
split plover
#

Did i make this array wrong? I dont know why this is happening cause it was just working not too long ago
int[] DamageArray = [20, 40, 20, 60, 100];

polar acorn
#

You can't use that syntax in Unity's version of C#

#

You need the new int[] {} syntax

split plover
polar acorn
#

Because that's how you create a new array in the version of C# Unity uses

split plover
#

What do you mean by create a new array?

#

im just gonna look it up cause it gives me a warning if i use new but if i dont use new it doesn't give me a warning

polar acorn
split plover
#

but i wanna use the array i made not make a new array

polar acorn
#

where did you make it

ivory bobcat
split plover
ivory bobcat
#

Collection expression isn't available in C# 9.0

polar acorn
split plover
ivory bobcat
#

Reminder that Digi provided the syntax not what to copy and paste into your script.

naive pawn
#

did you put new at the start of the line...?

split plover
# slender nymph what is the warning

it says it ddoes not hide an accessible member and says the new keyword isn't required but digiholic said that i have to use new so im confused

naive pawn
#

yeah you didn't put it in the right place

slender nymph
#

you put the new on the wrong part

polar acorn
naive pawn
#
- new int[] x = [...];
+ int[] x = new int[] {...};
split plover
#

its exactly like how you put it in syntax, new int[] DamageArray = {}

polar acorn
split plover
slender nymph
#

not quite

polar acorn
split plover
#

well it says i don't need the new keyword so im just not gonna use it

#

seems like its working fine without it

polar acorn
naive pawn
#

buddy i think you're conflating a few things

polar acorn
#

and is not what I said to use

#

I told you what to use instead of the expression syntax that isn't available in Unity's C# version

#

at no point did I say to change how you declared the variable.

#

Just what you assign it to

#

Notice how what I said to do does not have an = in it

#

because everything before your = was correct and shouldn't have changed

split plover
#

Im confused though

split plover
#

yeah no

#

i understand that

#

but im confused on why i'm being told that i wasn't supposed to do what i was told to do

polar acorn
split plover
#

im feeling like im getting conflicted answeers

polar acorn
#

You did something else that was not what I said to do

split plover
slender nymph
#

you misread what was told to you, you were not told to do something you shouldn't be doing

polar acorn
naive pawn
#

there are 2 ways to instantiate an array in c#
a collection expression, [...]
an instantiation expression, new T[] { ... }, which has a shorthand, { ... }

the former is not available in the version of c# that unity uses

polar acorn
#

It's the thing that goes after the =

slender nymph
naive pawn
split plover
slender nymph
ivory bobcat
#

Are you creating drama for no reason whatsoever? They're actually trying to inform you that you cannot use [ ... ] with c#9 and that you'd use the new int[]{...} pattern instead.

polar acorn
slender nymph
split plover
naive pawn
naive pawn
polar acorn
#

You should actually read answers you're given

split plover
#

While i was chatting here i finished my code i was making and it works perfectly fine

naive pawn
#

and let me guess, you don't actually understand the array initialization

naive pawn
split plover
#

i just put it as int[] DamageArrray = {} and it works perfectly

#

But if it works why am i being told to fix it.

naive pawn
split plover
#

thats my question

naive pawn
#

we're trying to get you to understand

split plover
naive pawn
#

your knowledge is lacking then lol

ivory bobcat
polar acorn
torn dragon
#

if i create a button why is this so big

split plover
split plover
polar acorn
naive pawn
polar acorn
#

It looks like a reasonable size for a normal overlay canvas

slender nymph
split plover
naive pawn
polar acorn
#

They're the size of the screen, not the size of the world

slender nymph
split plover
#

nvm mb i thought it was a button intended to be in the world

#

not enough context 😭

polar acorn
#

Where the button is in the actual world space doesn't matter, it's where it is in relation to the canvas

torn dragon
#

am making a start menu and it was fine before

#

now its super large

polar acorn
sour fulcrum
#

Is there a official way to do the equivalent of
List myList get; private set;
But where they can only reference the list to iterate and etc? Not add/remove etc.
Usually i’d have a function that returns a copy of the list but ideally it would be nice to not make a whole copy every time

#

It’s fine if there’s no preferred way either i just don’t know

polar acorn
slender nymph
#

use IReadonlyCollection<T> as the type rather than List<T>, List implements that interface

kindred axle
sour fulcrum
slender nymph
#

just have a private field that you expose through the property. also use IReadOnlyList<T> rather than IReadOnlyCollection<T>, i forgot that the latter doesn't allow you to index into it

sour fulcrum
#

Ohhh ok i misassumed how they work, thats cool tech

#

Ty chefs

split plover
#

quick question, is it even possible to set an array's values to another array

#

been trying to find a way for nearly 30 minutes

ivory bobcat
#

New array with the other as an argument for the constructor

#

Assuming you aren't just wanting to reference the same instance

split plover
slender nymph
#

there are beginner c# courses pinned in this channel, perhaps start there

split plover
split plover
slender nymph
#

and you still don't understand basic things like what an argument or constructor are. so perhaps learn c# separately from unity

split plover
#

im good seems like a waste of time for me when i only need c# for unity and nothing else

#

usually i dont need to ask here for my questions and i can just look it up but with arrays there is very little online 😭

sour fulcrum
#

(I get what you guys are trying to teach to Fusion but also the basic tutorials don’t teach you how you could use constuctors to copy an array)

slender nymph
split plover
sour fulcrum
#

What did you search

ivory bobcat
sour fulcrum
#

Googling is unironically a very crucial skill to build up

split plover
sour fulcrum
#

What did it come up with

split plover
#

a bunch of unity discussion forums that were on an entirely different topic

#

like one that is asking how to copy an array (not set an array to another array just straight up cloning an array without changing the name or anything)

ivory bobcat
#

For example cs int[] arr = {...}; int[] clone = (int[])arr.Clone();//Shallow copy

split plover
#

oh

#

nvm

split plover
naive pawn
split plover
naive pawn
#

no

kindred axle
#

theres lots of unity specific things in c#

#

so the courses won't go over everything

torn dragon
#

why can i not see OnStartClick() there

slender nymph
naive pawn
eternal falconBOT
split plover
#

man this would be so much easier if i didn't have to try to set one array to different arrays based on what is happening 😭

naive pawn
#

also, do you actually need a clone

#

if you just need a reference you can just.. assign the array

split plover
naive pawn
#

i have no idea what you're trying to say there lmao

#

stop saying "didn't work", that's not really useful
give some info about what the issue is

ivory bobcat
#

What're you trying to do exactly?

split plover
# ivory bobcat What're you trying to do exactly?

At this point i dont even know i just want something set up so that i can change stuff like movement speed based on what character is selected and right now im trying to set an array to another array but its super confusing

slender nymph
#

classic XY problem

naive pawn
#
  • why are you using an array for that (why not a struct)
  • why are you using an array for that (why not an SO)
  • so.. you can just assign that, no need to clone
split plover
#

fuck this i don't care about optimization im just gonna copypaste code like i was trying to avoid

naive pawn
#

the issue is you're painting yourself into a corner

naive pawn
split plover
#

well

#

if optimization isn't an issue im gonna just copypaste some code really qucik

naive pawn
#

structs are bundles of data, like arrays
the difference is you get names and you can have different types

naive pawn
#

the issue is you're fucking over your future self

#

and we've been trying to stop you from doing that and you're just hellbent on doing it apparently

rocky canyon
ivory bobcat
#

We're not sure what they're using their array for though - other than holding values.

split plover
naive pawn
#

why are you even asking stuff here if you're just going to ignore everything we recommend lmao

#

not gonna waste my effort if you refuse to accept help, cya

split plover
torn dragon
ivory bobcat
#

I do not believe anyone called you or referred to you as unintelligent UnityChanHuh

split plover
#

i called or reffered to myself as unintelligent

sour fulcrum
#

Anyone trying isn’t stupid 🫡

split plover
naive pawn
split plover
#

I already know what im going to do and its going to be much easier than what i was trying to do anyways so

vast cairn
#

should i manipulate the color via script

ivory bobcat
#

That's fairly interesting, although not code related #💻┃unity-talk
Perhaps you've got some lighting/shader in the scene that alters the color presented (how it looks like after fully rendered).
Either way, it isn't a code question.

vast cairn
ivory bobcat
lapis parrot
#

!code

eternal falconBOT
lapis parrot
#

when i use IEnumerator, it's saying i'm using the wrong namespace or type in my code (https://paste.mod.gg/tcphzgwrnwjh/0) i know that this is usually affiliated with misspelling, so if you can please help i don't see what i did wrong

ivory bobcat
#

Maybe post the specific error as well

#

An image of the console error in detail would suffice

split plover
#

from what i know you need using System.Collections at the top of your script to actually use IEnumerator

lapis parrot
#

oh

#

makes sense

split plover
#

might not fix your error but you do still need it from what i know anyways

lapis parrot
#

probably why it cant be found

lapis parrot
#

it did

rocky gale
#

what is the point of singleton

#

is it just so you dont accidentally duplicate

sour fulcrum
#

the idea is you don't need to search for something specific if only one of it exists

rocky gale
#

oh

sour fulcrum
#

if your looking for a guy named bobby who knows what kinda answer your looking for

if your looking for the current president of america theres only one result

#

if that makes any sense

rocky gale
#

yea that makes sense

#

thx

sour fulcrum
#

Google isn't giving me any answers that involve the interfaces themselves inheriting; Can I not do this kinda thing?

    public interface IBaseTest
    {
        public string GetCoolString();
    }

    public interface IEpicTest : IBaseTest
    {

    }

    public interface IRadicalTest : IBaseTest
    {

    }

    public class FullySickClass : IEpicTest, IRadicalTest
    {
        public string IEpicTest.GetCoolString() => "so cool":
        public string IRadicalTest.GetCoolString() => "woah";
    }
rocky gale
#

interesting idea

#

it doesnt work?

sour fulcrum
#

i know i can do

    public interface IEpicTest
    {
        public string GetCoolString();
    }

    public interface IRadicalTest
    {
        public string GetCoolString();
    }

    public class FullySickClass : IEpicTest, IRadicalTest
    {
        public string IEpicTest.GetCoolString() => "so cool":
        public string IRadicalTest.GetCoolString() => "woah";
    }
rocky gale
#

damn

eternal needle
sour fulcrum
#

I do have two different answers yeah, theres some other stuff in here that makes me wanna keep them not-seperate so if i can't do it like i wanted there i'll have to think of another way to handle this

eternal needle
sour fulcrum
#

ah that makes more sense

ripe dock
#
using UnityEngine;

public class HumanControl : MonoBehaviour
{
    public float moveSpeed = 5f;
    public Rigidbody2D rb;
    private HumanControls humanControls;
    private Vector2 moveInput;
    private void Awake()
    {
        humanControls = new HumanControls();
    }

    private void OnEnable()
    {
        humanControls.Enable();
    }

    private void OnDisable()
    {
        humanControls.Disable();
    }

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        Vector2 moveInput = humanControls.Land.Move.ReadValue<Vector2>();
        Debug.Log(moveInput);
        if (humanControls.Land.Dash.triggered)
        { 
            Debug.Log("Dash"); 
        }
           
    }
    void FixedUpdate()
    {
        rb.AddForce(Time.fixedDeltaTime * moveSpeed * moveInput);
    }
}

My character is not moving when there's any input, but it's still moved with gravity and such. What am I doing wrong?
My goal is to make an addforce-driven 2D top-down game character control

#

Both Debug.Log seem to be correct

slender nymph
#

you're creating a local variable called moveInput and assigning the input to that, logging it, then throwing that value away because you don't use it.
you also never assign to the field called moveInput so it's always the same as Vector2.zero when you use it in AddForce

ripe dock
chrome shadow
#

i currently have a rigidbody character controller, and i want the player to fall faster, i tried doubling the mass and jump force, meaning it should theoretically fall faster while jumping to a similar height, but the jump and fall speed ended up the same. How can i fix this?

My jump code:

    private void Jump()
    {
        // Apply jump force
        Ctx.Rb.linearVelocity = new Vector3(Ctx.Rb.linearVelocity.x, 0f, Ctx.Rb.linearVelocity.z);
        Ctx.Rb.AddForce(Ctx.transform.up * Ctx.JumpForce, ForceMode.Impulse);

        // Reset jump input and set cooldown
        Ctx.Input.jump = false;
        Ctx.JumpCooldownDelta = Ctx.JumpCooldown;

        // Trigger jump animation
        Ctx.Animator.SetBool(Ctx.AnimIDJump, true);
    }
keen dew
#

Gravity famously affects all objects the same regardless of mass

#

If you want to fall faster you'll have to either increase gravity or apply downward force while falling

chrome shadow
#

ahh ok

keen dew
#

Also check that the scale is correct, often when the objects look like they're falling too slow it's because they're too big. The player model should be about 2 units high which makes it feel the most natural

chrome shadow
#

the scale of the object with rigidbody is 1,1,1

keen dew
#

I meant scale in a more general sense

#

How tall is the object?

chrome shadow
#

well uh its a squirrel and its pretty tiny

keen dew
#

How tall is pretty tiny in numbers?

chrome shadow
#

the squirrel rig is scaled up 3 times

#

and its parented to an empty

#

with a scale of 1,1,1

keen dew
#

That doesn't tell anything

#

The model might be 1 cm tall or 100 meters tall

chrome shadow
#

uhhhh wdym

keen dew
#

Ok let's put it this way. When you jump, pause the game. What is the Y coordinate of the squirrel at that point?

#

when the jump is at the highest

chrome shadow
#

around 2.4

keen dew
#

Ok that's somewhat normal

chrome shadow
#

alr nice

topaz mortar
#

How does Physics2D.CircleCast work exactly?
Does it just return the first target hit in general? Or the first target for each "point" on the circle?
So if I had a target in front and behind me, would a circle cast return both? Or just the one hit first?

pallid nymph
# topaz mortar How does `Physics2D.CircleCast` work exactly? Does it just return the first targ...

I'd recommend reading the docs and/or just testing it.
There are different overloads - some get a single hit, some get all hits. I don't remember if it'll count the initial objects overlapping as hits, or only if the circle would hit something as it's moving. It's only moving in one direction, so it wouldn't hit something "behind" unless if it maybe overlaps the start point circle and those hits are included.

topaz mortar
#

yeah I checked the docs, just wasn't sure, thx

ripe dock
#

Trying to add player character dashing to my game, and I dont want it to poll the inputs every single frame whether or not they are pressed, so its not "if pressed" but instead "when pressed". So it's not as messy and more performant
This is what I have atm

    {
        Debug.Log("kek");
    }

etc
The debug message is not displayed
How do I fix it?

#

WDYM

#

Sorry, I'm very new to both Unity and C#

#

I guess the solution to it would be using the input events system. When pressed - invoke event, perform a dash

#

Oh, this

eternal needle
#

you definitely could do it through c# events as well but if you're very new to both then this unity event is easier for now

ripe dock
#

I added it from Project

#

Lemme try it out (my Unity successfully crashed lol)

eternal needle
#

yes thats not what you want to do. you want the unity event to reference your specific component as the link above shows in a video

ripe dock
#

Took me multiple hours to try and fix it myself

#

Maybe trying to make it event-based as a beginner was a bad idea 😁

eternal needle
nimble apex
eternal needle
#

though i see your code does actually use that HumanControls class

ripe dock
#

I completed the essentials tutorial and it used the old system. While simpler for beginners, it's just bruh

strong creek
#

I use camera relative movement and whenever I press backwards on the movement my character spins left or right

nova bluff
#

Hello everybody, i'm kinda new in unity development. i have a problem with my game. when i'm moving the character and camera, there is a jitter effect (i don t know if it's the correct term). I added a script for movement (https://pastebin.com/PA1v253c). do you have any ideas how could i solve this issue? thanks!

naive pawn
nova bluff
naive pawn
#

sidenote, don't use deltaTime with mouse delta input

#

it's already per-frame

nova bluff
#

changed, thanks

#

moving keyboard input to FixedUpdate and mouse input to LateUpdate fixed the jitter effect, but the camera is still not as smooth as i want to be.

#

do you use Cinemachine?

hexed terrace
#

The CM brain needs to be set to use the same Update method as your movement

past yarrow
#

Is there a Data Structure that combines both the stack and the queue concepts together so I can push / pop at the start and push / pop at the end please ?

sharp bloom
#

How much performance is lost by calling Animator.Play() with a string instead of hash?

#

Or does it matter very much?

hexed terrace
#

You'd probably need to be doing thousands of calls per frame for it to make a difference

sharp bloom
#

Yeah I thought it might be like that

sharp bloom
#

I found the PlayerInput component unintuitive, for me it was much easier to use the provided C# class directly

sharp bloom
eternal needle
# sharp bloom How much performance is lost by calling `Animator.Play()` with a string instead ...

https://docs.unity3d.com/ScriptReference/Animator.Play.html

When you use the stateName parameter, this method calls Animator.StringToHash internally
seems to be the only difference. the docs for StringToHash says it uses CRC32 so you could find performance related to that. or just run Animator.StringToHash() a bunch of times using the profiler to see the effect of calling it like 100, 1k, or 10k times per frame

wintry quarry
naive pawn
charred spoke
charred spoke
nova bluff
#

Still can't find a proper solution for jittering. If the other objects does not jitter, the character body it's jittering. If the character body does not jitter, the other objects will (as shown in video). I just can't make it work. https://pastebin.com/ztV4U3H9. Do you please have any ideas? Thanks!

wintry quarry
#
transform.rotation = Quaternion.Euler(0f, yRotation, 0f);```
rich adder
#

we need a bot command everytime this issues comes up lol

nova bluff
#

should use slerp?

wintry quarry
#

If you have a Rigidbody you should not be touching or modifying the Transform directly, period

wintry quarry
#

rotate the Rigidbody, not the Transform

#
Rigidbody.rotation = Quaternion.Euler(0f, yRotation, 0f);```
#

ALso you are doing this rotation in FixedUpdate

#

FixedUpdate is not synchronoized with the rendering loop

#

character rotation should happen in Update

#

So two things:

  • rotate in Update
  • rotate with the Rigidbody not the Transform
#

also ensure that interpolation is enabled on your Rigidbody

nova bluff
#

same problem.

  • Interpolation it's enabled on Rigidbody
  • I moved Rigidbody.rotation in Update function
  • Removed transform.rotation
    void Update()
    {
        ListenMouseMovementInput();
        CameraHolder.transform.SetPositionAndRotation(RigidBody.position + CameraHolderOffset, Quaternion.Euler(xRotation, yRotation, 0f));
        RigidBody.rotation = Quaternion.Euler(0f, yRotation, 0f);
    }

    private void FixedUpdate()
    {
        ListenKeyboardInput();
        MovePlayer();
    }```
nova bluff
#
    void MovePlayer()
    {
        if (moveDirection != Vector3.zero)
        {
            float speed = MoveSpeed * (Keyboard.current.shiftKey.isPressed ? RunSpeedMultiplier : 1f);

            Vector3 targetPosition = RigidBody.position + speed * Time.deltaTime * moveDirection;
            RigidBody.MovePosition(targetPosition);
        }
    }```
wintry quarry
#

you sure you want to be using MovePosition?

#

Instead of just setting velocity?

#

MovePosition is really only a thing for kinematic bodies

nova bluff
#

enabling kinematic in rigidbody removes jittering

#

but i don't have gravity

wintry quarry
#

I'm not telling you to make it kinematic

#

I'm telling you you shouldn't be using MovePosition unless it's kinematic

#

e.g. instead of:

            Vector3 targetPosition = RigidBody.position + speed * Time.deltaTime * moveDirection;
            RigidBody.MovePosition(targetPosition);```
You would do this:
```cs
Vector3 velocity = speed * moveDirection;
velocity.y = Rigidbody.linearVelocity.y;
Rigidbody.linearVelocity = velocity;```
rich adder
#

should rb.rotation be .MoveRotation, or is that just for interpolation ?

rocky gale
wintry quarry
naive pawn
#

velocity is the old version of linearVelocity

wintry quarry
#

it's the same thing

rocky gale
#

Oh really?

frail hawk
#

yeah, a major and very important thing unity had to change..

rocky gale
#

😂

wintry quarry
rich adder
#

ahh that makes sense ty

rich adder
rocky gale
#

It wasn’t angular before tho

naive pawn
#

it was

rich adder
rocky gale
#

Oh that

#

Wait

nova bluff
#
    void MovePlayer()
    {
        if (moveDirection != Vector3.zero)
        {
            float speed = MoveSpeed * (Keyboard.current.shiftKey.isPressed ? RunSpeedMultiplier : 1f);

            Vector3 horizontalVelocity = moveDirection * speed;
            RigidBody.linearVelocity = new Vector3(horizontalVelocity.x, RigidBody.linearVelocity.y, horizontalVelocity.z);

        }
    }```

Jittering it's still present and my character it's bouncy
rich adder
#

rb.velocity can be ambiguous if u are more technical with physics functions

rocky gale
#

Did they change rb.velocity or rb.angularVelocity

rich adder
#

no

naive pawn
#

before, we had velocity, angularVelocity, drag, angularDrag
after unity 6, it's linearVelocity, angularVelocity, linearDamping, angularDamping

rich adder
#

@rocky gale im saying they put linear to better distinguish it from from angular functions

rocky gale
#

Ok

torn dragon
#

how do i add a death screen and respawn key after my characters dies in game

#

the game is almost done

rich adder
rich adder
# torn dragon didnt help

break it down.
how do i add a death screen?
-- pretty vague question, but google " how to make activate/deactivate object in unity"

respawn key after my characters dies in game?
-- vague af still but, google "how to capture a keypress in unity"

#
DeathMethod()
ShowDeathScreen()
WaitForKeyPress()
HideDeathScreen()
RespawnCharacter()```
rocky canyon
#

it works!! 💪

    [Serializable]
    public class BindingSaveData
    {
        public string actionName;
        public string overridePath;
    }

    [Serializable]
    public class BindingsSaveFile
    {
        public List<BindingSaveData> bindings = new List<BindingSaveData>();
    }``` this is how im keeping up with the data. (and can see the text file next door)
just wondering if this is reliable +/or the way u guys would do it

- if you start and the file is there it loads in the file
- if you start and the file is missing it starts with the default binds in the actionmap
- once u finish it always loads the json..
(probably need a button for defaults but i **think** i shouldnt need to keep data on the defaults b/c they're already stored in the map..)
#

i currently using an actionmap with just a few button actions..
im actually unsure how the system works.. but the action maps all have just 1 bind..
that way when we rebind we can use keyboard, mouse, or gamepad (and all together)

only needing to overload the 0. i guess is whats stored in the memory

#

ive taken snippets here and there and built it up.. the syntax is something im still getting used to
and soo far i've only made it work with Button inputs... i figure the composite stuff is gonna be a bit harder

#

TLDR: im pretty sure im on the right path.. but i was just thinking of default values..
from what i understand the new system (if rebinding) just uses values in memory and doesnt actually change the map.. soo for default settings i actually dont really need to store those anywhere b/c they'll always be there..

proper compass
#

I need help, this is my Locomotion script but i slide when i hit off stuff. it is simular to Gorilla tag locomotion. However, it is in zero gravity etc. please see the code. if anyone can help me please let me know 🙂

eternal falconBOT
proper compass
#

but i still need help

naive pawn
#

you want it to have gravity?

#

you set it to not have gravity in Start

proper compass
proper compass
final trellis
#

how come when i try to make this line renderer not align with view it just vanishes

final trellis
#

or do i not understand the Transform Z Alignment option

scarlet tundra
#

Whats the best way to get a normal / curvature of an object, the normal with raycasting or?

rocky canyon
scarlet tundra
#

I guess I just answered my own question I'll be doing that then

rocky canyon
#

use the RaycastHit and just grab the .normal from it

scarlet tundra
#

Yeah, thanks!

#

What if I didn't want to use a mesh collider? ( I need to find the mesh's curvature ) it's kind of hard to explain, I can't use basic primitive colliders (e.g. box, sphere, capsule, and not mesh as it would be too performance heavy for what I'm trying to do.

rocky canyon
#

well u sorta have to..

#

raycasts detect colliders..

#

not meshs'

scarlet tundra
#

Yeah I know that's why I'm at a dilemma

rocky canyon
#

ya, that im not exactly sure of..

scarlet tundra
#

I could use spline to get the curvature but I'm not sure that would do exactly what I'd want

rocky canyon
#

ya i wouldnt know how to do that either.. i can google around a bit.. maybe someone else can chime in 🔔

scarlet tundra
#

You don't really know the context though, how would you?

rocky canyon
#

Barycentric Interpolation

#

lol.

scarlet tundra
#

What the?

#

For splines I see

rocky canyon
#

lol.. im not doing well w/ context either

#

^ might be something to this

scarlet tundra
#

Basically, VR, hand I already made the grabbing system with a pole that is flexible (as in size) it's just that it didn't quite handle curvature at all nor did it handle

rocky canyon
scarlet tundra
#

Yeah I don't know how I'd be able to take the speccific normal with raycasts

rocky canyon
#

ahh yea... this is like shader territory

scarlet tundra
#

Yikes I'm not ready for that

rocky canyon
#

im seeing things that say using a mesh collider and raycasts would probably be more performant than you'd expect

#

and alternative methods of going thru all the vertices and stuff would actually be less performant

#

unity, surface normal of mesh without collider is what im using to search with

scarlet tundra
#

And yeah since I'm literally only doing it one frame it wouldn't be that performance heavy

rocky canyon
#

but i did learn something.. that bary thing seems like a default way..
if you have a TRI.. u have 3 verts.. and using those verts u can calculate the normal

rocky canyon
scarlet tundra
rocky canyon
#

u never know

scarlet tundra
#

Yeah I'd better try hopefully using mesh colliders won't be performance heavy in general in the long run 🤷

rocky canyon
#

if ur concerned about them.. im not sure the operation ur doing...
but if its only needed at a certain time.. u could probably just leave it disabled until u need it

#

enable it.. do ur thing.. and then disable it again

rocky canyon
#

theres really only 2 options.. (align with Z and align with Cam) afaik

scarlet tundra
#

That's why I'm concerned for performance just random items around

rocky canyon
#

as long as u dont have 1000s of em im sure ur fine..

#

unity is pretty optimized in regards to physics

scarlet tundra
#

Alright thanks for your contribution!

final trellis
rocky canyon
#

it means like if ur looking at it from its local Z axis ull see it as it should be

#

if u end up looking DOWN it.. for example.. it'll be a sliver of pixel..

#

or the backside.. = nothing

final trellis
#

i should prob mention what its even for if the answer isnt gonna be as simple as i thought ( unless theres just a thing im missing that makes it work idk )

im trying to make a simple sword slash effect, where theres a list of points and every frame those points are added to the list of points a line renderer, so it gives the effect of a sword slash

final trellis
final trellis
final trellis
#

but rn its all weird and jittery

rocky canyon
#

with Z option chosen when we rotate the linerenderer object itself you'll see that it can only be seen from the front.. (0,0,-10) or something...

#

with the Align with View option.. we can rotate all the way around it.. (and it'll still be visible)
as its then acting like a billboard.. (like a 2D tree that rotates to always face the camera)

final trellis
#

how come its just.... not visible at rotation 0, 0, 0

#

for my end

#

im using a double sided material and at 0, 0, 0 rotation, theres no angle where its visible

rocky canyon
#

well, for 1 im showing an example thats rotating the linerenderer object..

#

ur not rotating the actual line renderer object..

#

ur just rotating the sword

final trellis
#

but its rotating alongside it? or does that not count

rocky canyon
#

i dont believe that counts.. its LOCAL would still always be the same

#

if its set to 0,0,0 and its a child of the sword.. no matter how u move the sword around.. its still gonna be 0,0,0 rotation.. relative to the sword

#

im not sure if that matters... or if its the global values its using..

final trellis
# final trellis

i think its gotta, bc you can see it rotating in and out of existence

#

this shits really weird

rocky canyon
#

im not gonna lie.. im not the best with line renderers 😄

#

i usually find a setup that looks good and move along

final trellis
#

it looks like how a 2d creature would percieve a 3d object moving along the axis it cant comprehend

rocky canyon
#

but ur using the trail renderer right?

#

and not actually the line renderer

final trellis
#

oh thats a thing?

#

😭

#

FUCK

rocky canyon
#

i believe they kinda work the same

#

but i dont know the specifics

#

a trail renderer would be what i assume ur looking for

#

if u want a trail for a swinging weapon

final trellis
#

lesson learned: someone mightve already done the thing youre looking to make and its even built-in

rocky canyon
#

😄

#

trails are set to automatically align with view..(iirc) so it may work right out the box..

modern aurora
#

complete beginner here, could use a hand with something simple that im a bit too dense to figure out atm.

using UnityEngine;

public class TileController : MonoBehaviour
{
    public GameObject endPos;
    public GameObject startPos;
    public GameObject tile;

    // Update is called once per frame
    void Update()
    {
        if (endPos.transform.position.z = 48);
        {
            Instantiate(tile, new Vector3(0, 0, transform.position.z), transform.rotation);
        }
    }
}

im getting an error CS1612 in the if statement. trying to spawn a new tile whenever endpos reaches z = 48

scarlet tundra
#

so it'd be endPos.transform.position.z == 48 (in your if statement)

modern aurora
#

🤦 thank you

scarlet tundra
#

Happens from time to time don't worry

naive pawn
#

don't beat yourself up, it's a rite of passage lol

#

still happens to me with a solid 4 years of experience

scarlet tundra
#

Exactly

wintry quarry
#

this code is very weird

modern aurora
#

the code is now spawning a tile on every frame

stuck field
#

Should head to !learn then, will teach you a lot going through the pathways

eternal falconBOT
#

:teacher: Unity Learn ↗

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

wintry quarry
#

Update runs every frame

#

It's not clear what the intent of this code is at all

modern aurora
#

infinite runner game. rather than moving the player, im moving the world around the player, so when a tile reaches a certain point im trying to spawn a new tile in its original place

glossy current
scarlet tundra
#

Use the new input system for one (its powerful in some scenarios) and for another don't separate the different euler rotations into different classes

glossy current
#

Am I not using the new input system? I looked up a guide and I thought I was. I separated them because the up and down moves the characters head and the left and right moves the entire character.

scarlet tundra
#

Hold on

naive pawn
#

yeah that's the new input system

scarlet tundra
#

Yeah I just realized it was

#

But in general the rotations shouldn't be handled in two separate scripts

glossy current
#

How should I then separate it if I want one to rotate the whole body and the other to only rotate the head?

rich adder
#

btw you should not be using Time.deltaTime on mouseInput

#

do you have any other scripts on the player ? also use links don't use screenshots for !code 👇

eternal falconBOT
glossy current
#

Ok, can you explain why? I'm a little confused on how it works, I get it standardizes things between frame rates but i'm just a little confused on when to use it and when not to

#

I have an unused character health script and template script that only contain a few variables right now.

#

no methods or anything

rich adder
naive pawn
# glossy current Ok, can you explain why? I'm a little confused on how it works, I get it standar...

deltaTime is the time in seconds since the last frame, so it's in units of seconds per frame - it's a conversion factor
sometimes you have things in x per second, and you need to convert that into x per frame - that's where you use deltaTime
but sometimes you don't need to convert
sometimes you want things in x per second, like rb velocity
sometimes you already have things in x per frame, like mouse input

glossy current
#

Oh ok I see

#

Ok I got rid of that but any idea why I'm getting the stuttering and lockup?

#

and if I should combine the two rotation scripts, how should I split movement between the head and body

rich adder
hollow field
#

Does Input.GetKeyDown() only return true on the first frame the key is pressed?

glossy current
#

the left and right rotation is on the body, which is the parent to the head. the head has the up and down rotation script

hollow field
rich adder
rich adder
hollow field
#
else if (Input.GetKeyDown(KeyCode.Space) && gameRunning) {
    Debug.Log("[SPACE] pressed during game!");
    if (score + 0.5 <= currentTimer.timer && currentTimer.timer <= score + 1.5) {
        currentTimer.timer = 0.0f;
        rotateMark.direction *= -1;
        score++;
        infoText.text = "Click when the timer reaches " + (score + 1) + " seconds.";
        rotateMark.resetMarker();
    }
    else{
        Debug.Log("TOO EARLY!!!");
        GameOver();
    }
}```
If player presses space while game is running, check if they pressed it within a certain time window.  If they press too early, run the GameOver() method. The issue is, it triggers the first if but then re-runs the whole thing and since the first if sets the timer to 0, it will trigger the else segment
rich adder