#💻┃code-beginner

1 messages · Page 653 of 1

grand snow
#

You can also use different layers and make the battle stuff only draw with some other camera

#

If player data is kept elsewhere then it would be safe to let the player object be destroyed and remade later

lapis sentinel
#

https://www.google.com/url?sa=t&source=web&rct=j&opi=89978449&url=https://developers.meta.com/horizon/downloads/package/meta-voice-sdk/&ved=2ahUKEwimtMaT-oKNAxX9R2wGHbo6C-sQFnoECBsQAQ&sqi=2&usg=AOvVaw1oSzzmsDzxbbJWpHGtiYlS

ok im struggling to understand and use this package. The issue is Meta doccumentation is only in oculus SDK while im working on using Meta XR SDK both are different but provide the same feature and value. i cant use oculus because i dont have the gear that utilize it. Soo im struggling to find the directory name and namespace associated with the directory

wintry quarry
#

still not sure what you mean by "directory" though

#

do you mean "package"?

lapis sentinel
#

yeah

#

package

#

the using part in every unity c#

#

😅

naive pawn
#

that's a namespace

wintry quarry
#

not packages

grand snow
#

c# basics time i think

naive pawn
#

packages can define namespaces

lapis sentinel
hexed terrace
#

why you asking a non-code question in a code channel? 😄

slender nymph
#

not a code question. but double click your canvas to focus it, it's likely a screen space overlay so it won't be positioned in world space

grand snow
slender nymph
#

or is this question actually about the lighting and not the lack of canvas visible in scene view? 🤔 (even still, it's not a code question)

grand snow
#

🌩️

hexed terrace
#

delete the question from here too - so you don't get told off for cross posting

lapis sentinel
#

using Meta.WitAi;

public Wit AppResponder;

so if i write like this ,what does the Wit stand for?

slender nymph
#

that would be a type. if you don't know what types are, then stop what you are doing and start with the beginner courses pinned in this channel.

grand snow
#

You can also just do SetActive(false)

#

many ways to hide something or restrict what a camera can see

twin pivot
#

im trying to use Mathf.Lerp to have a npc follow the player in a vector 2 format but im not sure on how id use the time parameter

#

would i just slowly increase the time by 0.1 until the npc reaches the destination and then reset it to 0?

polar acorn
twin pivot
#

thank you Heart

slender nymph
#

it would probably be more appropriate to use MoveTowards rather than Lerp for that

teal viper
keen cargo
#

hey yall, back again with another code logic question

so I have three scripts:
GameManager, which has references for the monster and player
RoomManager, which has a reference to a Room object - this generates a random room for the player and monster to teleport to
Room, which stores 3 transform values - 2 for the player and monster's teleport locations

currently, RoomManager has the Teleport() function, which teleports the player and the monster between rooms, however it needs a reference to the player and monster (which it doesn't right now)

I had an idea of maybe moving this function to GameManager, since it'd probably make more sense there - however then i'd need to reference the Room object from RoomManager, which I feel makes the object call quite verbose

This is the script I have in RoomManager right now, note that player and monster aren't referenced, so this is non-functional at the moment

public void Teleport(GameObject player, GameObject monster)
{
    SaveOffset(player, monster);    
    playerRb.MovePosition(currentRoom.playerSpawn.position);
        
    float distance = offset.magnitude;
    float monsterSpeed = monster.GetComponent<Monster>().speed;
    float waitTime = distance / monsterSpeed;
    StartCoroutine(DelayingMonsterTeleport(monster, currentRoom.monsterSpawn.position, waitTime));
}

specifically at the Coroutine with currentRoom, I think the call would extend to something like RoomManager.instance.currentRoom.monsterSpawn.position

would there be a better approach than this? Perhaps using observer pattern again?

wintry quarry
keen cargo
#

Teleportation is currently called from the RoomManager script

the flow goes like:

player enters a door -> gamemanager says "ok, roommanager can you teleport them, and then generate a room for them as well" -> roommanager generates a room, calls teleport

#
public void TriggerEvent(Type trigger)
{
    switch (trigger)
    {
        case Type.Die:
            monster.KillPlayer();
            player.Die();
            break;
        case Type.StartLevel:
            monster.StartMonster();
            // Roommanager.instance.generateRoom();
            //generateRoom(false);
            break;
        case Type.NextLevel:
            //generateRoom(true);
            break;
        case Type.PreviousLevel:
            //generateRoom(false);
            break;
        case Type.ResetLevel:
            player.ResetPlayer();
            //restartRoom();
            break;
        case Type.WinGame:
            SceneManager.LoadScene("MainMenu");
            break;
}
#

This is part of the gamemanager

#

I'd be okay with referencing the player and monster again, just to keep Teleport in RoomManager, but just wanted to ask if there's probably a better way to do this

twin pivot
#

the conditions arent getting triggered for some reason

polar acorn
twin pivot
#

i just did that actually

#

looks like the coroutine is just not getting triggered for some reason

#

wait no it is

twin pivot
rich adder
#

also ur not assigning that v3 movetowards return value to anything

twin pivot
#

oh i see

twin pivot
rich adder
#

I think max delta is fine to be constant actually but ig needs time.deltaTime to keep it so

twin pivot
twin pivot
#

yes

rich adder
twin pivot
#

ignore the last error, its supposed to be there

rich adder
# twin pivot

I can't tell how many times .. 0.4 seems wrong as start tho no?

twin pivot
#

once, but i think i know what i did wrong now

#

i start the coroutine using a script in the copy of the text box

#

and that gets killed

rich adder
#

huh this moving code is in a textbox script?

#

btw you probably want some type of a star here or third party 2d navmesh. this will take the most direct route ignoring walls or water

twin pivot
twin pivot
rich adder
olive axle
#

Does anyone have a good guide on making hud elements? I just want to see a number while moving?

nimble apex
#

i dont know whether im overdoing this, or got some unnecessary steps

currently i have a setup to initialize my "player" gameobject using SO, my game is pure idle + farming + social game, as i said
so theres no battles, my characters dont even need "attributes"

its guaranteed that 1 character will only have 1 dedicated animation set

and because each characters will have different hierachy like these + skinned mesh renderer

i will need to make prefab to each of them, otherwise its too difficult to use SO to swap/populate every components/materials/textures

#

my question is, do SO really needed here

#

i already needed a prefab for each of the characters anyway.....

#

one of the possible benefits, i think its multiplayer, if i stored prefab under a SO

#

because in my game, im allowing multiple players to choose same characters

#

i think its still usable

#

i will have different skin(avatar/forms) of characters, which is swapping out meshes , and maybe animation sets

hollow trout
#

is it bad practice to have public static bool for player states such as inAttackAnimation and isRolling even if its for a player script and there is only one player?

nimble apex
#

so at the end it might be

- ID
- original character prefab
- List: possible skins
- List: possible animation controllers```
sour fulcrum
hollow trout
twin pivot
#

tmp(text mesh pro) is the absolute king when working with ui

wet pivot
#

Hello again yall 😅

naive pawn
naive pawn
wet pivot
naive pawn
#

it just causes more noise, you can always put pleasantries in your actual question message

wet pivot
#

Seeing some weird behavior from my code...

Vector3 wallNormal = wallRight ? rightWallHit.normal : leftWallHit.normal; Vector3 wallForward = Vector3.Cross(wallNormal, transform.up); rb.AddForce(wallForward * wallRunForce, ForceMode.Force); Debug.DrawRay(pm.transform.position, wallForward * 500, Color.green, 10f);

the wallForward vector works for applying force to my character, but it is not working for the draw ray

naive pawn
#

wdym by "not working"? is it not showing up, or is it showing up in the wrong place?

wet pivot
#

I'm hoping to use this vector to rotate my character in the direction of the wall forward, but that's not working either.

#

Does not show up at all, character doesn't rotate either when I do this
playerObject.forward = Vector3.Slerp(playerObject.forward, wallForward, Time.deltaTime * 10f);

naive pawn
#

this in Update?

wet pivot
#

it's 3 levels down in nested functions but the top level function is running in update

hollow trout
naive pawn
#

i feel like you'd be better off with a singleton for that

naive pawn
wet pivot
#

ah its returning 0,0,0

olive axle
naive pawn
#

!collab, and don't crosspost

eternal falconBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

green karma
#

Guys I tried downloading visual studio 6 but Microsoft Visual Studio community 2022 is giving a error "Download Failed: Validation Failed"
I tried searching online and it said to run unity with administrator but it didn't work. Also tried installing manually but it won't download and stays at 0-kbs

teal viper
#

What visual studio 6??

#

And VS 2022 giving download failed errors??

nimble apex
#

u guys think it is forgivable to do such thing in a scriptable object🤣

    [field: SerializeField] public List<int> VariantIndex { get; private set; }
    [field: SerializeField] public List<Material> OtherMaterial { get; private set; }

    //use this instead of the key/value list
    public Dictionary<int, Material> MaterialVariations()
    {
        Dictionary<int , Material> temp = new();
        
        for (int i = 0; i < VariantIndex.Count; i++)
        {
            temp.Add(VariantIndex[i],OtherMaterial[i]);
        }
        
        return temp;
    }```
#

it worked tho...... welp desperate moments with desperate measures

grand snow
ivory bobcat
# nimble apex it worked tho...... welp desperate moments with desperate measures

https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.-ctor?view=net-9.0#system-collections-generic-dictionary-2-ctor(system-int32)

int count = VariantIndex.Count < OtherMaterial.Count ? VariantIndex.Count : OtherMaterial.Count;
Dictionary<int, Material> temp = new Dictionary<int, Material>(count);
for (int i = 0; i < count; i++)
    temp.Add(VariantIndex[i],OtherMaterial[i]);
return temp;```
nimble apex
#

ty i will look at this first

naive pawn
faint tulip
#

what should i do if i want my character to face a certain direction when it spawns on a location>??

#

i rotate its position in the scene but it keeps facing north than what i put him in the scene

wooden star
#

Ive wrote this code to make the camera follow the player but it does not follow the player and the camera falls indefinetly on the z axis

naive pawn
nimble apex
#

ty guys 👍 at the end i made up my minds and use a plugin lol

#

im not doing any tests or exams in class, im making games, so i gonna use what asset stores already have

naive pawn
#

also for future reference, !code

eternal falconBOT
naive pawn
wooden star
#

nvm

#

i fixed it

naive pawn
#

yeah it's really straightforward

wooden star
#

i didnt think it would work but it did

#

im not very familiar with the syntax

naive pawn
#

then check out beginner c# resources in CheckPins

wooden star
naive pawn
#

don't have any recommendations, in general text articles will be easier to skim through, backtrack, or search content

frigid sequoia
#

Can I make an int property have a range of it only having numbers from 0-8 or do I need an enum for that? Cause feels kinda silly using an enum for actual numbers lol

slender nymph
#

You can put the range attribute on its backing field if you mean for the inspector. if you want to clamp it to that range in the actual code, then just clamp it in the setter

frigid sequoia
#

It would be better if it always remains within the range, since it's basically an id than can never go beyond 8, but I guess the range attribute would do

slender nymph
#

then clamp it in the setter like i said

#

but use the range attribute too so that the backing field is restricted to that range for the inspector

#

if clamping via the setter, I would personally log a warning if an attempt to set it outside of that range occurs

frigid sequoia
#

Shouldn't be the case that I try to change it in runtime, I think

slender nymph
#

sure, but just in case you do the warning would be useful

cosmic dagger
frigid sequoia
#

It should be never set in code, I am just REALLY having a headache on how to implement what I am doing, since you have 8 commands (with ids 1-8). These are on a list that is never touched, but then I have another list for active commands, player can add a command to this list, and it would add the lowest id number avaliable to the list, but they can also remove ANY at any time from the list, basically letting to an unorganized list where you could have like 1, 2, 4, 3, 5, 6 and the items having a different a Index on the list than id is fucking my mind lol

slender nymph
#

at this point it is really starting to sound like an enum might be more appropriate. if these "ids" are supposed to represent specific commands then it really should be an enum. that's what enums are, ints with labels

tulip nexus
#

i know that this isnt the right channel but i cant find one fitting for my question, would it be possible to change the tilling value for all new materials? so instead of 1 its 0.3

#

so when a new material is created in any way it has 0.3 by 0.3 on by default

slender nymph
kindred iron
#

Why doesnt it work? here is the code:

public class GameManager : MonoBehaviour
{
    public int money;

    [SerializeField] private AudioSource audioSource;
    private Animator animator;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

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

    public void Click()
    {
        money++;
        animator.Play("SlimeClickAnimation");
        Debug.Log("Clicked");
        if (audioSource.isPlaying == false)
        {
            audioSource.Play();
        }
    }
}
slender nymph
#

have you confirmed the button actually works?

slender nymph
#

i mean exactly what i said

kindred iron
#

it should work

slender nymph
#

have you done literally anything at all to confirm it does

polar acorn
#

Is the button responding to the mouse, like changing colors on click or anything

kindred iron
polar acorn
slender nymph
#

well with your current setup it wouldn't change colors on click because it has no target graphic

kindred iron
polar acorn
kindred iron
#

should i make like collider 2d

polar acorn
# kindred iron no

So, add one, and set the target graphic for your button to the image you want to actually click on

kindred iron
#

oh its component

#

ok i added

polar acorn
kindred iron
#

i added then?

#

what does even event system

polar acorn
#

It allows you to click on UI elements

kindred iron
#

but it still doesnt work

polar acorn
#

Did you do the second step

kindred iron
polar acorn
#

And assign a target graphic to the button

polar acorn
kindred iron
polar acorn
#

It gets created when you first create any UI object, so don't delete it

slender nymph
#

your button is also not on a canvas

polar acorn
kindred iron
kindred iron
#

i guess i did

polar acorn
slender nymph
#

wait why is the event system component attached to the button?

#

there is just so much wrong here

#

and none of it is code related

kindred iron
slender nymph
#

you should do what digi suggested and create it separately from the Create menu

polar acorn
# kindred iron where should i attach it then?

It should be an object that gets created when you first add any UI elements. But also since you don't seem to have made any that's why you don't have it. They would also come with a canvas

kindred iron
kindred iron
kindred iron
polar acorn
kindred iron
#

ok, i deleted the event system from the game object which is called SlimeClick

#

now it does

polar acorn
#

You can only have one event system. It won't create one if it already exists in the scene

frigid sequoia
slender nymph
#

or you use descriptive names in an enum instead of cryptic letters and numbers

frigid sequoia
#

The idea is that the player can make these do and look whatever they want to, so... it's not like I can give them a name that makes sense

slender nymph
#

in that case you need to actually be descriptive about wtf you are trying to accomplish so that a proper solution can be suggested because at this point it is impossible to tell what the actual fuck you are doing since you refuse to actually describe it

frigid sequoia
#

Well, picture this: right side UI shows a list of commands, you can add up to 8, these commands have different things you can do and you are meant to be able to change how they look (picture them sorta like WoW macros). You can add them 1 by 1 (it would automatically add the lowest id that is not yet active as the last one on the list and UI). You can remove any of them at any time. This right UI is the part where you configure what these do, but you actually have to use them on the bottom UI.

Bottom UI would have to update to the order of the right UI, so if you have a list of Ids 2, 6, 4 on the right, the buttons showing on the bottom should be those corresponding to those commands and be on that same order. The Id reference must hold what the heck those specific commands are meant to do.

And to make this even more confusing, I am also adding like extra funcions to the commands that basically is a list of commands inside a command that would be executed on that order alongside it (they use the same script, but are tagged as id 0, so you can know they are not the main ones). So for example if the command says "Move X to Y", you can have 2 functions inside of it also saying "Move Y to Z" and "Attack Z" and it would be executed on that order with a single buttom press.

#

That's the idea, how to make that work is still to solve for me lol

floral wren
slender nymph
#

it sounds like all you need is two arrays, you don't need this ambiguous "id" variable. when something changes in the "right side UI" you just update both arrays

slender nymph
#

what? no, arrays are fixed size and are "ordered" in the way you specify since you put things into specific indices

kindred iron
#

Why does the animation just play 1 time?

public void Click()
{
    money++;
    animator.Play("SlimeClickAnimation");
    
    if (audioSource.isPlaying == false)
    {
        audioSource.Play();
    }
}
sharp bloom
#

Is this a bad practice?

// "piece" script
    void LateUpdate()
    {
        gm.gameGrid.gameHexes[currentPosition].setPieceOnHex(this);
    }
// "tile" script 
void Update()
    {
        pieceOnHex = null;
    }

I want to track which "pieces" are on which tiles. This way each of my tiles update instantly to "null" whenever there are no piece on it.
But somehow this feels a bit...hacky?

floral wren
# frigid sequoia Runtime

You could implement a MVVM layer to bind your data reducing the needs to manually keep your UI refreshed. (Making it trivial to sync multiple UI as well)

wintry quarry
wintry quarry
kindred iron
wintry quarry
wintry quarry
kindred iron
sharp bloom
wintry quarry
pastel dome
#

why does it always say its null

#

i put the slider in the box

slender nymph
#

what is "it" in this context

wintry quarry
pastel dome
#

it is the debug console

wintry quarry
#

what is?

#

show us

frigid sequoia
slender nymph
#

if only there were links in the search results that explain the architecture and how it works

pastel dome
wintry quarry
#

as the log says, it's the object called "Idle" where it's not assigned.

pastel dome
#

so make it look in children?

wintry quarry
#

huh?

pastel dome
#

oh

slender nymph
#

i'm just curious why you put the gameobject's name in your log if you didn't plan on actually looking at that part of the log

floral wren
pastel dome
#

i didnt realize it cus i was working on gettting the spider working not the dummy

#

its a soft lock system that id s targets

frigid sequoia
#

As far as I have read this is basically what I am already trying to do?

sharp bloom
frigid sequoia
#

Like it's just a type of workflow

pastel dome
#

im not much of a coder just trying to get this working for my class

wintry quarry
sharp bloom
#

Currently nowhere, I just tested it by manually dragging the gameobjects

wintry quarry
# sharp bloom Currently nowhere, I just tested it by manually dragging the gameobjects

You should basically do this:

public void SetPosition(Vector3Int newPosition) {
  var oldPosition = currentPosition;
  gm.gameGrid.gameHexes[oldPosition].setPieceOnHex(null); // set old position to null - we're removing ourselves
  currentPosition = newPosition;
  gm.gameGrid.gameHexes[currentPosition].setPieceOnHex(this); // assign ourselves to the new position
  // move physically

  transform.position = gm.gameGrid.gameGrid.CellToWorld(transform.newPosition);
}```
#

Then you only move by calling SetPosition

#

now everything works

sharp bloom
#

Ah that should work, ty

tribal fulcrum
#

hello, i need help with this project. im making a plinko game rn and i want an animation to play when the ball hits a peg. currently the peg and animation arent connected to each other and idk how to go about this

wintry quarry
rich adder
#

Uhhh Is this like a bug or something? 🤔

#

i tried both .text = and .SetText restarted unity.. same result

naive pawn
rich adder
#

also what is going on with that null ref on clicking the text lol i have no idea

rich adder
#

was thinking also might had to do with something with Events / Async

naive pawn
rich adder
#

here is code for context

  private string messages;
    void OnEnable()
    {
        inputText.onSubmit.AddListener(InputTextSubmit);
        gameHubController.OnConnected += OnConnected;
        gameHubController.OnMessageReceive += OnMessageReceive;
        connectedText.text = "disconnected";
    }
    private void OnMessageReceive(string msg)
    {
        messages += msg;
        messages += Environment.NewLine;
        messagesText.SetText(messages);
    }```
naive pawn
#

was it just clicking or did you press enter?

rich adder
#

oh I did not press enter at all

naive pawn
#

oh

rich adder
#

I tried both

#

I used SetText cause .text wasn't working thinking maybe was event issue but no, it works fine for the connectedText

naive pawn
#

maybe need to mark something dirty

naive pawn
rich adder
#

yeah thats what I was thinking tbh..I am using async for that

lost haven
#

Simple question. Im trying to get input for My game. Input needs to switch camera 1 to 2 after pressing a certain key. Whats The simplest code for that

rich adder
# naive pawn <:thonk:638524515797827633> when is `OnMessageReceived` called? is it perhaps no...
 protected async Awaitable InitHubAsync()
    {
        HubConnect();

        // Handle incoming messages
        hubConnection.On
        <string, string>("ReceiveMessage", (user, message) =>
        {
            var mesg = $"user: {user} \n message: {message}";
            Debug.Log(mesg);
            OnMessageReceive?.Invoke(mesg);
        });

        try
        {
            await hubConnection.StartAsync();
            isConnected = true;
            OnConnected?.Invoke(isConnected);
            Debug.Log("Connected..");
        }
        catch (Exception ex)
        {
            Debug.Log($"Connection error: {ex.Message}");
        }
    }```
naive pawn
#

idk about async stuff, can't help with that, sorry lol

rich adder
#

This is the only thing thats different so I'm gonna take your suggestion this is probably to do with threads, its weird cause it told me that Debug.Log can't be called on non-main thread..until i used Awaitable (it used to be Task)

naive pawn
#

if the thread thing turns out to be the issue, you could probably just move messagesText = messages; to Update

ripe shard
naive pawn
#

could make it "simpler"

#
CinemachineCamera camA;
CinemachineCamera camB;
private void Update() {
  if (Keyboard.current.spaceKey.wasPressedThisFrame){
    camA.Priority = camA.Priority == 0 ? 1 : 0;
    camB.Priority = camA.Priority == 0 ? 1 : 0;
  }
}
lost haven
#

Is that simpliest?

naive pawn
#

probably not

lost haven
#

I mean for me it seems like a simple as frick thing to do

ripe shard
#

simplest is meaningless, use the one you understand

naive pawn
#

but really "simple" can mean a lot of things yeah

ripe shard
#

also this is just the code, it makes assumptions about the scene config

lost haven
#

Yeah i know, for me The code im thinking would Be just like "If you press this The camera changes and If you press it again The camera would change to original"

#

But im just a newbie so : D

ripe shard
#

any trickery that eliminates this dedicated variable is, in my book, less simple, harder to understand and more prone to breaking.

rich adder
naive pawn
ripe shard
#

a code golfers definition

marble pollen
#

I have this game that I'm making for an assignment due tonight (i procrastinated too hard whoops) - Its a top down 2D tile-based movement game where you can push around some crates, activate switches with those crates to open gates, step on portals and teleport to them later, and pick up items which increase the total moves you have per level. I have all of those things except the crates working properly and i would hugely appreciate some help with it. Right now, I have them being pushed just fine but I would like to only allow one to be pushed at a time, which I am seriously struggling to implement. I have a really screwed up movement system but I dont have time to make a better one and I'm kind of freaking out about it

eternal falconBOT
marble pollen
#

for eample, the walls, rather than having physical colliders, have triggers which interact with the player's hitbox which is + shaped. These triggers prevent the player from making a move into a wall. For the crates, I move them around using normal colliders but am trying to make them do basically the same thing as the walls. To try and achieve this, I've made 4 child objects for each crate which also sit around it in a + shape so it knows which direction things are in, and i'm trying to make it so that when it triggers against another crate AND the player object on the opposite side it prevents the player from moving towards the crate and therefore pushing more than one

#

its jacked up

marble pollen
#

there's the player movement script

#

thats the main crate controller

#

and thats an example of one of the crate children (this one is on the right side, so theres 3 more for the 3 other sides)

#

its a really messed up setup but like I said I do not feel like I have the time to make a better one since I still have to do level design and some menus

rich adder
marble pollen
#

in hindsight i understand this was dumb but i dont have the time to fix it

rich adder
#

off center ?

marble pollen
marble pollen
rich adder
marble pollen
rich adder
#

ohh rigidbody collision you mean

marble pollen
#

yeah

#

in any case the walls work fine so janky system or not im not worried about that

rich adder
#

but now you have the same problem to solve with moving boxes

marble pollen
#

what I'm trying to do is make it so when triggers attached to the crates detect a crate on one side of it and a player on the other side, it basically tells the player that theres a wall there so it cant move into that tile

#

essentially preventing the player from making a move to push multiple crates

#

when its just a single crate the pushing mechanics work fine and the crates also detect walls just fine

#

this is literally my second time making anything in unity so everything is like weird LMAO im sorry

rich adder
noble needle
#

hey guys, do I need to run the AddEventListener only once if I want some functino to be run when some event happens?

rich adder
noble needle
#

nvm I just realised something, oops

paper sable
#

hey, im making a player movement script and for some reason whenever i start jumping while moving around, if i stop pressing the WASD keys but still hold the jump key, my rigidbody continues to move in the direction i was going initially, kinda like a bunny hop. does anyone know why this might happen? this is the code that handles jumping. the HandleJumping method is being called in FixedUpdate

private void Awake()
{
        input = new InputActions();

        input.Player.Jump.performed += ctx => isJumping = true;
        input.Player.Jump.canceled += ctx => isJumping = false;

        rb = GetComponent<Rigidbody>();
        rb.freezeRotation = true;

        ResetJump();
}
private void HandleJumping()
{
        if (isJumping && readyToJump && grounded)
        {
            readyToJump = false;

            rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);

            Invoke(nameof(ResetJump), jumpCooldown);
        }
}
private void ResetJump()
{
        readyToJump = true;
}
rich adder
#

the best way for you to solve it is to breakdown the steps you will need to verify and debug it

#

examples, which values are what you expect them to be vs not

high summit
#

howdy! i'm trying to figure out why this is firing

#

the int value of "Score" is 1

slender nymph
#

only that first line is actually in the if statement's scope

rich adder
high summit
#

Wait really?

slender nymph
#

yes, this is c# where white space does not denote scope

high summit
#

I'm new to c

rich adder
#

without {} if statement only counts whats directly after it

slender nymph
#

it's also not c, it's c#

high summit
#

Yeah my bad

#

So i need likee

#

1 sec

slender nymph
#

as nav has pointed out twice now you need curly brackets

high summit
#

Like this?

#

Thanks btw 🙂

paper sable
high summit
#

Also working on a flickering flashlight script, I know i'll need a loop, I'm using an IEumerator currently, Is this a bad way to add a delay?

#

this obviously isnt a loop yet

rich adder
#

this will only happen once btw

high summit
#

I did something like this on a static light in my scene is this better?

rich adder
#

Time.deltaTime usually works fine

high summit
#

tyty 🙂

rich adder
#

also would try testing it in a build just incase its not an editor thing

#

back when , I recall un focusing the game window by accident would cause that key not to release

paper sable
#

whenever i stop pressing wasd but keep holding space, the velocity remains the same but slowly goes to 0 on the x and z values

rich adder
paper sable
#

AddForce

rich adder
# high summit I did something like this on a static light in my scene is this better?

btw I found a script I made a while ago a more "randomized" pattern using intensity, if you're interested into that as well

private IEnumerator Flicker()
    {
        while (true)
        {
            for (int i = 0; i < lights.Length; i++)
            {
                float flicker = Mathf.PerlinNoise(Time.time * flickerSpeed, 0);
                float intensity = Mathf.Lerp(minIntensity, maxIntensity, flicker);
                lightMesh.material = intensity < maxIntensity / 2 ? lightOffMa : lightOnMa
                lights[i].intensity = intensity;
            }
            yield return null;
        }
    }``` 
made a few years back so its not cleanest but might come in handy
(you can probably ignore the material part unless you want to do that as well to "swap textures"
rich adder
elfin isle
#

https://paste.mod.gg/lzgjeirrszsx/0 APOLOGIES FOR MY MESSY ASS CODE

so basically, i have a fish swimming down a stream, and it is supposed to fall when it gets to a certain point (line 76), i have tried what i think is everything at this point and ive even used debugs, and my code should be running but it isnt. could anyone help?

paper sable
high summit
#

This is weird

rich adder
high summit
#

Ooh i'll have a dig

rich adder
#

you can search the hierarchy with t:DoorLogic

high summit
#

Yep I found it instantly! Thanks, That's a nice thing to have learnt and I guess happens alot more than people expect

rich adder
#

its pretty common yea lol

high summit
#

Also forgetting to hit 'stop' and editing while in playmode has tripped me up a few times now

elfin isle
#

i think i had a similar thing happen to me a day or two ago lmao

rich adder
rich adder
#

should've been default tbh

grand snow
#

I make my tint more red for that reason

elfin isle
rich adder
#

its pretty messy to scan through all this, are you checking the logs?

#

..use debugger is probably less of a pain to go back n forth adding lines instead of just breakpoints

elfin isle
#

yeah, and basically what the logs are telling me is that the code should be running, im getting the debug but its not moving any differently

rich adder
#

always verify the values we expect are actually the values that are happenig

elfin isle
#

i did that too but i can check again rq

rich adder
elfin isle
#

wdym?

rich adder
#

just cause the function might be running doesn't mean the values are what you expect them to be

elfin isle
#

thats a good point

rich adder
#

thats why youd normally log whats in that function etc.

#

string myName= "bob" ;
void MyName(){
Debug.Log(myName)
vs
Debug.Log("its running")

paper sable
rich adder
#

its fairly easy esp with Animation Curves / MoveTowards and such

high summit
#

Am i allowed to share a janky preview of how my games coming along here?

rich adder
high summit
#

Sweet thanks!

elfin isle
high summit
#

When you dont know how to UV map properly or use the correct shader so you just place walls connected at this size everywhere (pain)

verbal dome
high summit
#

I remember rea

verbal dome
#

Doesn't need UVs

rich adder
high summit
#

I was about to type that

high summit
verbal dome
#

What renderpipeline are you on? The default Lit shader probably has it. Set UV mode to triplanar in the material settings

high summit
#

I'm on URP/lit

rich adder
paper sable
elfin isle
rich adder
#

and it was moving ?

rich adder
#

would also log Fish.transform.position and see whats happening there
eg like before 77 and 78

verbal dome
high summit
#

Yeah I dont think it does, I did look a little last night

verbal dome
#

You gonna have to google

elfin isle
#

i wasnt updating "num" at the right spot

high summit
#

I'm almost done with my first game so i'll just leave it how I have it currently, It's a pain to work with but i'll look into triplanar next game lol

elfin isle
#

that simple replacement took two hours

rich adder
rich adder
frigid sequoia
#

Can I make an UI element no be part of the EvemtSystem?

#

Cause entities have a canvas in world space over them but they don't ever need to be interacted

slender nymph
#

Untick the raycast target on the graphic objects

neat sluice
#

when i try and run some code for the camera to follow i get hit with the same error can i get help with what it means? (ill get it real quick)

#

where my cursor is at is line 21 sorry i forgot to screenshot the numbers too

naive pawn
neat sluice
naive pawn
#

there's a lot of ways to do that, try googling for some

neat sluice
#

okay thanks

analog pivot
#

I made a (possibly) simple menu with buttons based on races and classes of a game I like that sets stats based on race. I can get the race to set the class availability list and make stats appear (although someone said my method seems too hardcoded???)

How can I get it so its like “if race/class combo then these religions are available and these stats are adjusted by class”

Im sorry if I cant explain better but I really am that newbie at code

https://cdn.discordapp.com/attachments/831230543227519047/1244506529965543524/My_project_-_Char_Create_-_Windows_Mac_Linux_-_Unity_2022.3.12f1__DX12__2024-05-26_23-11-11.mp4?ex=68164346&is=6814f1c6&hm=ad975dd903e8f8314496f37b3873d99f81c849050a7a658722b41c3916b0bbf9&

#

I made this almost a year ago but I had some real life and so its been on back burner and now it feels like I don’t even remember how I made this

#

And Ive tried to understand code but its like impossible to clikc

high summit
#

made a png with some text for my horror game in photoshop dragged it in as a sprite renderer (i assume thats the correct way) and it kinda.. glows from far away?

#

Is that due to the shader?

rich adder
high summit
#

Ah color was set to 'white' instead of black

#

I think that was it

#

We good

analog pivot
#

Is my question too complex? Im sorry if Im not wording it well

rich adder
#

sounds like a simple math thing

analog pivot
#

Yea but when I try to do “add total” it doesnt work. I can try to look at the code when I get home but again Im not sure how to explain

rich adder
azure dust
#

Hello guys,i am beginner and learning from Unity pathway (https://learn.unity.com/pathway/junior-programmer/unit/sound-and-effects/tutorial/lesson-3-3-don-t-just-stand-there-1?version=6).
I have problem with animation when player falls down and its change from falling (Death_01) to laying on ground (Dead_01), player wil start runing again. Thats mean that fell animation wont continue and will restart to running. I follow all instructions from tutorials/pathway.

Unity Learn

Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.

high summit
#

Making a horror game is slowly making me feel insane lmao

rich adder
#

whoever wrote that must not be in such a hurry

#

also not really a code question

high summit
#

Tryna find a font 😦

#

and yeah you right

rich adder
rich adder
azure dust
rich adder
azure dust
#
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    private Rigidbody playerRB;
    public float jumpForce = 10f;
    public float gravityModifier = 2f;
    public bool isOnGround = true;
    public bool gameOver = false;
    private Animator playerAnimator;
    void Start()
    {
        playerRB = GetComponent<Rigidbody>();
        Physics.gravity *= gravityModifier;
        playerAnimator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && isOnGround && !gameOver)
        {
            playerRB.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
            isOnGround = false;
            playerAnimator.SetTrigger("Jump_trig");
        }
    }
    private void OnCollisionEnter(Collision collision)
    {
        if(collision.gameObject.CompareTag("Ground"))
        {

            isOnGround = true;
        } else if(collision.gameObject.CompareTag("Obstacle"))
        {
            gameOver = true;
            Debug.Log("Game Over!");
            playerAnimator.SetBool("Death_b", true);
            playerAnimator.SetInteger("DeathType_int", 1);
        }
    }
}
``` Here is entire PlayerControll.cs script.
rich adder
#

the inspector for them

azure dust
#

transitions is default, didn't change anything. I will show you.

rich adder
azure dust
#

Death to dead

#

Here is Alive to Death_1

rich adder
azure dust
#

Dead_01 is like this

#

An player still runing

rich adder
#

are you sure the correct animation ?

#

so many layers on that animator it throws me off

azure dust
#

I followed instuctions from video, only if i miss something somewhere. But i am sure that i have same and i chechek couple times

#

Only way to try fix this is by replacing animation with new one, the original one and check again

rich adder
spiral oracle
#

idk how to fix this, the error message is "Cannot implicitly convert type 'UnityEngine.Vector2' to 'float' " and rb is a RigidBody2D

#

could someone help me here please?

#

movespeed is a float

rich adder
azure dust
eternal needle
spiral oracle
rich adder
#

linearVelocity is what ur looking for. Also you should remove Time.deltaTime from the calculation for rigidbody

spiral oracle
#

I meant to use rp.velocity

spiral oracle
#

thanks

#

I'll make those changes

azure dust
#

And its never stops

azure dust
#

when falling animation starts, Run_static is still working.

#

I reseted all animations settings and still didn't fix

rich adder
azure dust
#

From running to jumping when press spacebar, that is working fine, but main problem is with Dead_01 animation. Run_static is deafult state

obsidian holly
#

im back again, i think my game just needs someones expert eyes because whatever i do/change regardless if I did it or chatgpt does it (which i cannot look at chatgpt rn hate it), doesnt seem to be playable when putting it into like itch.io or anything free 😭 (but playable when i run it ofc) if anyone’s free and can help me, ill send ss and everything your way… i just seriously need help

analog pivot
#

what i cant do is make the class side button disable religions or adjust the base stats based on the selected combination

azure dust
#

@rich adder sorry for tag. Thank you for helping and i am sorry that i waste your time. I fixed the problem by reinstalling all animations.

analog pivot
#

i also tried to do a less 'hardcoded" way of setting stats but... doesnt work

neat sluice
#

does anyone know a good place to learn code along with the unity learning hub?

#

google has failed me this time unfortunately

eternal falconBOT
#

:teacher: Unity Learn ↗

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

twin pivot
#

With youtube coming in last since most people just copy and paste and not learn what a certain line of code

neat sluice
#

but ye have to do the coding to learn the coding :<

#

im slowly learning my inputs now tho

twin pivot
#

Slows you down a lot at first but helps later down the line

neat sluice
twin pivot
#

Search it up on google

neat sluice
#

alr im downloading it rn

neat sluice
twin pivot
teal viper
sour fulcrum
#

I can't get away with an override like this in interfaces right

public interface SubInterface
{
    public abstract SubBehaviour Get();
}

public interface SubInterface<T> : SubInterface where T : SubBehaviour
{
    public override SubBehaviour Get() => GetBehaviour();
    public abstract T GetBehaviour();
}
neat sluice
analog pivot
eternal falconBOT
#

:teacher: Unity Learn ↗

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

twin pivot
#

But also why not make a int list and store the values in there?

analog pivot
#

I can try. Never done it before

analog pivot
#

Fair enough

mossy jasper
#

I need help on my code

north kiln
eternal falconBOT
north kiln
#

Then once you can see your errors and have autocomplete you can match every brace up appropriately

mossy jasper
#

it says "No problems found, and plus, i configured my visual studio to unity

rich adder
#

if it was configured what you saw in unity console would show in IDE

mossy jasper
#

dam

#

well, ok, i will configure my ide now...

#

i read the page and i think my ide is configured

rich adder
mossy jasper
#

oh

rich adder
#

if its not underlining red in the editor then its not configured

mossy jasper
#

ok

#

yeaaa, i kinda need some help on IDE

mossy jasper
#

i checked for updates and visual studio is up to date

rich adder
#

that has nothing to do with it

#

from link sent, and do each one and it will work

echo cradle
#

sorry to populate this with another collision troubleshooting issue but I'm trying to learn the new input system and got lost on how to properly code my setup. so i discovered rule tiles and wanted to make a system like this, i'm going for pixel perfect movement but the players box collider keeps passing though walls.

naive pawn
echo cradle
#

so teh Physics2D.OverlapCircle is no good now?

naive pawn
echo cradle
#

its the box collider im interested in using, and changing it to the the boxes transform didn't change anything so i guess its in the colCheck....?

naive pawn
#

also you aren't giving any layermask to the overlap circle so that could hit yourself

naive pawn
echo cradle
#

my box collider keeps passing though walls

naive pawn
#

what did you mean by "changing it to the boxes transform"?

echo cradle
#

you said i shoudlnt control teh trasnform myself, so i updated it

naive pawn
#

if the box collider is on the same component then it's the same transform

echo cradle
#

so then its a problem with the colCheck function?

naive pawn
#

you don't need the colCheck function

echo cradle
#

then how do i check for walls?

naive pawn
#

you don't have to

#

the rb will detect and respect collisions on its own if you use velocity or addforce

echo cradle
#

but im going for pixel perfect movement, like they'll stop on the center of a tile when i release the key?

naive pawn
#

that isn't pixel perfect thonk that's moving on a grid

#

are you having diagonal movement with this?

echo cradle
#

nha

#

input controller took care of that

naive pawn
#

ok so you don't want physics-based movement, why use rbs then lol

echo cradle
#

mostly i jsut want the box collider?

naive pawn
#

then just use that

echo cradle
#

it passes though my walls

naive pawn
#

that isn't solved by arbitrarily adding an rb and then ignoring its existence

echo cradle
#

fine ill remove the rb

naive pawn
#

btw what's with putting it in FixedUpdate, why not just put that in the playerinput message

echo cradle
#

nope, still passes though twalls

#

because if i did that i would have to press the button EVERY tile

naive pawn
naive pawn
naive pawn
#

do your walls have colliders?

echo cradle
naive pawn
#

ok so start debugging - try logging out what the overlap circle returns, try logging out that position and see if that's right

echo cradle
#

im logging the dir vector but i dont know how thats helpful

#

its true on floor, false on walls, except when i go up

#

if i raise the radius on the overlap circle i cant move down

naive pawn
echo cradle
#

i do

rocky wyvern
# echo cradle i do

Why are you doing all this complicated input logic instead of just using a pixel perfect camera

#

Is it actually important that your character snaps to a grid

#

If you absolutely must do that

#

Then just let physics and rb handle all collision

#

Trust me coding collision yourself isn’t worth it

#

You can still snap the player to a grid when you stop moving even if you allow rb to handle physics

#

There’s nothing stopping that from working

echo cradle
#

i was tryign to sort out how to use teh new input system and for some reason my collision code just isn't working for the top

#

how will a pixel perfect camera fix this? this sint about the camera its about the walls and my gird

rocky wyvern
echo cradle
#

because i'm going for a rpg type gameplay, with events and interactables and i just wanted the old school pixel perfect feel?

trail heart
# echo cradle how will a pixel perfect camera fix this? this sint about the camera its about t...

The idea with pixel perfect camera is that it also snaps all the sprites, so even if the true position of objects is not on a grid it doesn't perceptually make a difference
This means the physics and collision could be handled by rigidbodies
Alternatively, if you're overriding transform position in your script, you're also overriding rigidbody physics entirely so you need to code your own physics, whatever that requires in your case

echo cradle
#

so scrap this and start again with a 'pixel perfect camera' tut? can i still use rule tiles with it or no?

trail heart
#

Neither method is exactly better, though using Unity's physics and pixel perfect component is less work but harder to get exact results with

trail heart
echo cradle
#

i apparently CANT tue these by hand

trail heart
#

Meaning?

echo cradle
#

my player still passes though walls when going up

#

no idea why

trail heart
# echo cradle my player still passes though walls when going up

As far as I can tell you're still a bit in between systems
If you do your collision detection manually, set your rigidbody to kinematic or remove it entirely
Then start troubleshooting all parts of your system, mainly does the overlap detect the wall correctly
It seems like it would not, if your character is not allowed to move if it does

#

(If you do use a rigidbody for your character, you are meant to use rigidbody class methods for moving it, so Rigidbody2D.position or Rigidbody2D.MovePosition instead of Transform.position
This shouldn't affect functionality, but to my knowledge improves accuracy and performance because rigidbodies are meant to be responsible for their own movement)

rancid quail
#

Hey! my pathfinding seems to not work properly, the agent's never pick the shortest path, instead they pick a random one

#

what can i do to make them always take the shortest path?

karmic sparrow
#

hello regarding optimization in a scene this big with lots of stuff in it my current optimization is to have data reading of each stage puck to be in a singleton and once read from db just pass it to each puck but its still kinda slow any more optimizations that can be done? it takes about a 1sec to 1.5 to fully load

swift elbow
inland latch
#
EPERM: operation not permitted, rename 'F:\Uni Work\Computing project\Computing project VR Unity Project\Library\PackageCache\com.unity.xr.management' -> 'F:\Uni Work\Computing project\Computing project VR Unity Project\Library\PackageCache\.del--21412-uGbm5poMmWEt'
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()```
anyone know why any package i try to install fails with this error
#

actually some work, and i managed to install xrpluginmanagement forcefully by installing something that had it as a dependency, but most others still fail?

#

now unities forzen and has tried installing this one thing about 20 times

#

itll load, disappear, freeze a little, then pop back up again

inland latch
#

ok so, anytime i open project settings unity maxes out my ram and freezes

inland latch
#

so i don't think it's my pc not being good enough

#

i've also got this error

The file might be corrupt or have a missing Variant parent or nested Prefabs. See details below.
Errors:
    Nested Prefab problem. Missing Nested Prefab Asset: 'XR Origin (XR Rig) (Missing Prefab with guid: d6878e1999eb4b44a9f5a263af86c185)'
    Nested Prefab problem. Missing Nested Prefab Asset: 'Hand Menu With Button Activation (Missing Prefab with guid: e2698219e3231e94c8765d49b9dd5cff)'

boy do i love when everything just breaks at once out of the blue and nothing seems to fix it

#

the package installing issue seems to have fixed itself but i still can't open project settings without unity dying and running 0.1fps, and im still getting an import error on a prefab

slender nymph
#

this is a code channel

inland latch
#

where would i go for these issues

slender nymph
inland latch
slender nymph
#

then you didn't bother reading that

inland latch
#

i did

#

it says go to

#

"browse channels"

#

which is just the list of all channels and i still dont see one for unity help

slender nymph
#

try reading more than just the first sentence you see

inland latch
#

brother i read it all there's no unity help channel

slender nymph
#

you don't need to lie, it's clear you did not read past the very first sentence in that channel.

#

also you remember how in grade school your teachers would tell you to read all of the instructions before beginning a test or whatever? yeah, this is why

inland latch
#

does it say where to go for general unity help

slender nymph
#

copy and paste the second sentence in the channel i linked.

inland latch
#

it says to use find a channel

#

i wouldn't count general questions and unity help as the same but ok

slender nymph
#

mate, general question that belong in this server are unity help questions because this server is a unity server. also nowhere in that does it specifically say "general questions" or "unity help"

tulip nexus
#

i'm trying to make a editor script that sets the tilling for all new materials that have a texture located in assets/textures/surfaces to 0.3 x 0.3, can som1 tell me what i'm doing wrong, it does not return any errors

using UnityEditor;
using System.IO;


public class SurfaceTextureTiller : MonoBehaviour
{
    static void OnPostprocessAllAssets(
        string[] importedAssets,
        string[] deletedAssets,
        string[] movedAssets,
        string[] movedFromAssetPaths)
    {
        foreach (string path in importedAssets)
        {
            if (path.EndsWith(".mat", System.StringComparison.OrdinalIgnoreCase))
            {
                Material mat = AssetDatabase.LoadAssetAtPath<Material>(path);

                if (mat == null) continue;
                Texture mainTex = mat.mainTexture;
                if (mainTex != null)
                {
                    string texPath = AssetDatabase.GetAssetPath(mainTex);
                    if (!string.IsNullOrEmpty(texPath) &&
                        texPath.Replace("\\", "/").ToLower().StartsWith("Assets/Textures/surfaces"))
                    {
                        mat.mainTextureScale = new Vector2(0.3f, 0.3f);
                        EditorUtility.SetDirty(mat);
                        AssetDatabase.SaveAssets();
                    }
                }
            }
        }
    }
}```
wintry quarry
#

what's calling this function?

tulip nexus
#

i put it in the editor folder i thought unity would pick up the OnPostprocessAllAssets method and run it from there

wintry quarry
#

Your script is a MonoBehaviour not an AssetPostprocessor

tulip nexus
#

ok so after changing the monobehaviour thing to assetpostprocessor the string array lit up and it runs but it still doesnt seem to change the tilling

high summit
#

howdy!

#

So in my game you pick up this clipboard and you can read it

#

It's a game object

#

but I need it to not be affected by light?

#

As you can see it uh.. Is clearly unreadable lol

rich adder
high summit
#

Oh I see i'll give that a shot thanks

#

What exactly is a 'world canvas'

#

I see normal cavas

#

Oh world space

#

gotcha

#

Oh wait you said 'on it'

#

not put it in one

rich adder
high summit
rich adder
high summit
#

Wont that make only the text ignore light?

#

Not the clipboard itself

rich adder
#

uhh if thats the case you'd have to use Unlit material

#

its going to look pretty out of place, if you want that look though should be ok

high summit
#

My shader settings are locked for the individual pieces of the board I was gonna try that

#

on mesh renderer

rich adder
#

You'd have to duplicate the material or extract it from mesh to modify them

rocky canyon
#

^ nothing stopping u from using a lit material on the text right?

#

cant u do that?

high summit
#

Wont that look bizzare..

rocky canyon
#

iono.. thast how regular ink works

high summit
#

in a dark room with bright glowing text on a dimly lit piece of paper

rocky canyon
#

noo i meant lit the text would also be dim

#

if therse no light

high summit
#

Hmm you mighr be right

thick spoke
#

yo, for some reason when i bake, its not showing me what i baked? any ideas? i am using navmesh surface, and also i am tryna make a cube follow it, for some reason it isnt, i am guessing.

high summit
#

In this case its probably more realistic to pick this up and have to walk into light to read it

#

Fits more with the horror vibe I guess

rich adder
#

either target or agent is null, or both

rich adder
rich adder
high summit
#

Yeah haha it fits perfectly

rich adder
thick spoke
rocky canyon
rocky canyon
#

like if ur flashlight runs out of battery and u cant read the next clue or something.. (softlocked)

rich adder
#

it will show all objects with that component

rich adder
rocky canyon
#

National Treasure-esque

#

Lemon Juice and Blacklights

rich adder
#

and that clue will lead to another clue. dont you see ? treasure is a myth

queen adder
#

using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed;
public float rotationSpeed;

private Rigidbody rb;
private float moveInput;
private float rotationInput;

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

void Update()
{
    // Inverted vertical input so W = forward
    moveInput = -Input.GetAxis("Vertical");

    // Left/right rotation input (A/D or Left/Right)
    rotationInput = Input.GetAxis("Horizontal");
}

void FixedUpdate()
{
    // Move forward/backward
    Vector3 move = transform.forward * moveInput * moveSpeed * Time.fixedDeltaTime;
    rb.MovePosition(rb.position + move);

    // Rotate left/right
    float rotation = rotationInput * rotationSpeed * Time.fixedDeltaTime;
    Quaternion turn = Quaternion.Euler(0f, rotation, 0f);
    rb.MoveRotation(rb.rotation * turn);
}

}

How can i modify this code in order make my tank to can't reach high hills

eternal falconBOT
high summit
#

So this clipboard spawns in my face so i can read it

#

It has a box collider and so do all other objects

#

but i can put it through walls etc

#

Nvm just moved it as close to the camera as possible and made it scaled down

slender nymph
#

why not make it UI instead of a world space object?

#

also this is a code channel

high summit
#

I considered that but the way it attaches to the camera gives it that subtle sway movement which looks really good

grand snow
# high summit

This is when you fudge the render order (to be after most opaque but pre transparent) + ignore depth or use a second camera to render it later.

rich adder
#

ofc camera stacking is the easiest but then sadly you wont get Shadows from the world
Oh and sadly if one uses Deferred rendering , doesn't allow camera stacking :\

near thicket
#

What's the best way to make a 2d interface in a 3d game? Should I just create some flat gameobjects and place them right in front of the camera?

wintry quarry
#

UGUI (the standard) or UI Toolkit (the latest and greatest but still not totally feature complete maybe)

near thicket
wintry quarry
near thicket
#

I'm just hoping to do some sorta basic GUI stuff eg a panel with 3d models that you can drag into a building space

wintry quarry
#

If the 3d models need to be dynamic/animated, it's a little more complex

#

if you just need images of them, you can create those images ahead of time and import htem as regular sprites to be used in the UI

near thicket
wintry quarry
#

yes

#

The way works is basically using a second camera to render to a RenderTexture, then using a RawImage component in the UI to display the texture that the camera rendered

near thicket
#

alright thanks

wintry quarry
#

Alternatively if it needn't be interactive you can use a VideoPlayer

high summit
#

I have a question regarding cavases and issues with them, Can't find a correct place to ask, any help?

slender nymph
azure forum
#

Thank you for the help on my script guys

rocky canyon
#

no worries.. thats why we're here

naive pawn
#

(see what spawncamp linked about posting your code)

rocky canyon
azure forum
rocky canyon
#

yup

azure forum
#

Learning a bunch of stuff here haha, thanks a lot everyone

#

Ans such a fast response, you guys are awesome

naive pawn
#

i'm not seeing any debug logs there

rocky canyon
#

depends on how hard we're procrastinating on our own projects 😉

naive pawn
#

-# <- has unity open and hasn't touched it in a few days

azure forum
naive pawn
#

no?

#

stuff doesn't magically happen, something has to cause it to happen

#

the console automatically shows errors and warnings, and probably a few specific logs, but anything else has to go through Debug

azure forum
#

Where should I add debug then? And more importantly, how? 🙂

visual ginkgo
#

hi guys, i just installed unity and i'm following a course video on youtube. everything good until my new first script. i got this error, can someone help me? i would appreciate it a lot :(((

azure forum
naive pawn
naive pawn
# azure forum Where should I add debug then? And more importantly, how? 🙂
  • where it's relevant, aka where the issue might be. debugging doesn't solve issues, but it lets you narrow down where they come from and what might be the cause
  • you can use Debug.Log, and pass in a string, which would be the message of the log - use an interpolated string, like $"string content {variable}" which lets you peek into the program and see values. the "string content" part could be used to label where the log is from or what value you're logging
azure forum
#

FYI here's the hierarchy window and the inspector for my sprite child

naive pawn
#

hmm real quick, since we didn't actually mention this - in the animator window, when you run, does isRunning show up as true, or does it just stay false?

azure forum
#

I had this in my code at one point but removed it: // Récupère l’objet enfant "Sprite" (doit exister dans la hiérarchie)
spriteTransform = transform.Find("Sprite");
if (spriteTransform == null)
{
Debug.LogError("⚠️ L'objet enfant 'Sprite' est introuvable !");
return;
}

    animator = spriteTransform.GetComponent<Animator>();
    if (animator == null)
    {
        Debug.LogError("⚠️ Aucun Animator trouvé sur l'objet 'Sprite' !");
rocky canyon
#

as i was learning i used them EVERYWHERE every function, everyloop, every condtion, every gameobject and value.. probably too much tbh but u sure get lots of information

naive pawn
rocky canyon
#
  • where it's relevant, aka where the issue might be. debugging doesn't solve issues, but it lets you narrow down where they come from and what might be the cause
  • you can use Debug.Log, and pass in a string, which would be the message of the log - use an interpolated string, like $"string content {variable}" which lets you peek into the program and see values. the "string content" part could be used to label where the log is from or what value you're logging
    string interpolation is a game-changer
naive pawn
#

also for future reference, small snippets should be formatted like the latter half here:
!code

eternal falconBOT
rocky canyon
naive pawn
rocky canyon
#

small code blocks ^ like dis

azure forum
naive pawn
#

yes

rocky canyon
#

that is the animators parameter yup

#

thats this

azure forum
#

When I run, nothing happens animation wise, it stays on idle. I think I set up the isrunning properly and I'm using the exact same name as the one I have in my code

#

is this checkbox supposed to do anything?

naive pawn
#

you aren't answering my question... does the isRunning parameter stay unchecked?

naive pawn
azure forum
#

yes it says unchecked

rocky canyon
#

  if (animator != null)
  {
      Debug.Log("Animator was found");
      animator.SetBool("isRunning", direction.magnitude > 0.1f);
      
      Debug.Log($"We just set the animator's isRunning boolean to: {direction.magnitude > 0.1f}");
  }            
naive pawn
#

yep ☝️ basic debug in this case

rocky canyon
#

give urself as much information as u think u need that will help figure out little bugs and errors in ur code

naive pawn
#

though you'd probably also want to debug direction (and perhaps its magnitude to avoid having to calculate that yourself)

rocky canyon
#

true.. i was hoping they had a variable for those

#

its own boolean..

#

same for the isRunning boolean..
i tend to use 1 for the script.. and then use that one to just set it directly for the animators..

azure forum
#

I added the small code you gave me in the script and still nothing in the console window

rocky canyon
#

nu uh..

#

u put it here in the fixedupdate??

#

if none of the code runs.. that means that that condition never evaluates as true

azure forum
rocky canyon
#

that means this MUST be null then

azure forum
#

Oh wait can we co-edit the code on that website? 😮 that would be awesome if it worked

rocky canyon
#

put an else statement on the end of it

keen dew
#

Now you do have an error and you still have error messages disabled in the console

rocky canyon
#
  if (animator != null)
  {
      Debug.Log("Animator was found");
      animator.SetBool("isRunning", direction.magnitude > 0.1f);
      
      Debug.Log($"We just set the animator's isRunning boolean to: {direction.magnitude > 0.1f}");
  }
  else
  {
      Debug.Log("This is the only other thing that could be happening");
  }     
rocky canyon
naive pawn
#

the error message should have some info

azure forum
#

wait guys it works!!!!

rocky canyon
azure forum
#

Oh my god I don't know why

rocky canyon
#

lol

azure forum
#

I re-applied the script to Player and I now have my run animation. Absolutely no idea why, I tried that a few times before...

rocky canyon
#

well, glad we could help <question mark> 👍

naive pawn
#

that sounds like an unsaved script

rocky canyon
#

yuppers

azure forum
#

And I can see the logs!!!

rocky canyon
naive pawn
#

that's a lotta errors

rocky canyon
#

yup he was gatekeeping the rest of the errors with broken code

#

now that its not broken anymore the flood-gates are open

azure forum
rocky canyon
#

and then when u tab to the Editor it should RECOMPILE

#

on its own

azure forum
#

Alright understood 😮

#

That's so awesome to see it working, thank you guys

rocky canyon
#

this thing ^ should pop up even if briefly

#

if not u'd want to manually Refresh Ctrl + R in the editor

azure forum
#

I'll try flipping the sprite to the left with the script I found earlier, I'm confident it'll work now... hopefully

naive pawn
rocky canyon
#

try it on a simple non-player object first

#

get it working.. then move it to ur player..

#

that way atleast if it doesnt work on the player.. u knew it did before hand.

azure forum
#

wow 😮 seems like there were a lot of errors indeed

rocky canyon
#

kind of a way to pre-debug

rocky canyon
azure forum
rocky canyon
#

nothing wrong with using basic cubes and empty gameobjects to write some code 👍

azure forum
#

I started with that but I didn't learn the code per say, I just found bits and pieces online that I put together. Time learn C# then haha

rocky canyon
#

also. heres a tip.. u can Collapse identical debug logs.. that way they dont flood ur console..

#

it'll just add a number to the far right.. showing how many of those logs exist

#

with this button here

azure forum
#

ohhh that's great! Much easier to go through indeed

naive pawn
eternal falconBOT
#

:teacher: Unity Learn ↗

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

rocky canyon
#

ChatGPT is better as an assistant than a tutor

azure forum
#

I started the online course (learned editor essentials) but I wanted to try my hand at something in the meantime, to keep things entertaining

#

Anyway I'm really glad I could find a solution, and you guys helped me understand how it all works a lot better. I'll be sure to post here if I have other issues, thank you so so much!

rocky canyon
dry cloak
#

Is this the rightspot to ask about coding issues?

#

its very beginner stuff

rocky canyon
#

as long as they aren't intermeddiate or advanced yea

naive pawn
#

"code" and "beginner", seems about right

dry cloak
#

Im making a sliding mechanic in my game, and I used this line of code:

playerObj = new Vector3 (playerObj.localScale.x, slideYScale, playerObj.localScale.z);

and i have an error saaying: Cannot Implicitly convert type 'InityEngine.Vector3 to 'unityEngine.Transform

I am very new to this, and havent seen it before

naive pawn
#

for future reference, post formatted !code:

eternal falconBOT
naive pawn
#

and also, don't retype error messages. copy them. you may lost important detail when copying.

#

anyways, seems like you've declared playerObj as a Transform, but you're trying to assign a Vector3 to it - that's what the error means.
"I want a UnityEngine.Transform, but you gave me a UnityEngine.Vector3. I don't know how to convert this."

dry cloak
#

mhm

naive pawn
#

(backticks, the key beside 1 on a qwerty keyboard)

dry cloak
#

so i just need to use transform instead of Vecotr 3?

naive pawn
#

no, you can't construct a transform

dry cloak
#

playerObj = new Vector3 (playerObj.localScale.x, slideYScale, playerObj.localScale.z);

#

Error (active) CS0029 Cannot implicitly convert type 'UnityEngine.Vector3' to 'UnityEngine.Transform' Assembly-CSharp

naive pawn
#

what exactly are you trying to do with that code?

naive pawn
dry cloak
naive pawn
#

so you're trying to modify the scale?

dry cloak
#

yes

naive pawn
#

so in that case, well... you'd have to assign to the scale, rather than the entire transform

#

(look at your tutorial closer)

dry cloak
#

from the video

naive pawn
#

compare that to your code

dry cloak
#

oh my lord

#

ty

#

im a little slow in the head notlikethis

naive pawn
#

eh it happens lol

#

you'll get better at identifying that with experience

dry cloak
#

So i want to be able to jump while sliding, to be able to jump, i must be grounded, and ready to jump

#

When I'm sliding, grounded is not true

#

this is what sets grounded to be true
grounded = Physics.Raycast(transform.position + Vector3.up * 0.1f, Vector3.down, playerHeight / 2, WhatIsGround);

#

and this is my sliding movemnt ``` Vector3 inputDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;

rb.AddForce(inputDirection.normalized * slideforce, ForceMode.Force);

slideTimer += Time.deltaTime;

if (slideTimer <= 0)
StopSlide( );

#

how would i be able to make myself grounded when on the ground?

tulip stag
#

I cant figure out what the bug in my code is, or if the code is even in this snippet here. 😵‍💫 When this function is called, everything seems to be working fine except that ageInHumanYears always outputs 0. ageInDays works fine and so does ageInYears. The input for days is 8766. Can anyone spot any bugs I'm missing?

public static void SetAgeFromDays(Character target, int days)
{
    target.ageInDays = days;
    target.ageInYears = Mathf.RoundToInt(days / 365.25f);
    if (target.ageInYears < target.ageOfAdulthood)
    {
        float percentage = (float)target.ageInYears / target.ageOfAdulthood;
        target.ageInHumanYears = Mathf.RoundToInt(percentage * SimulationManager.Instance.ageOfAdulthood);
    }
    else
    {
        float postAdultYears = target.ageInYears - target.ageOfAdulthood;
        float simulatedPostAdultSpan = target.ageExpectancy - target.ageOfAdulthood;

        float percentage = (float)postAdultYears / simulatedPostAdultSpan;

        int simPostAdultSpan = SimulationManager.Instance.ageExpectancy - SimulationManager.Instance.ageOfAdulthood;
        target.ageInHumanYears = SimulationManager.Instance.ageOfAdulthood + Mathf.RoundToInt(percentage * simPostAdultSpan);
    }

    SetLifestate(target);
}```
keen dew
#

Log all the values that are used to calculate it. If any of them seem incorrect, log all the values that are used to calculate that value and so on until you find the problem

eternal needle
tulip stag
#

Bet 🫡

jovial yacht
#

hi guys

#

i have a problem with my camera

#

I put the Far Clipping Planes on 40

cosmic quail
near thicket
jovial yacht
# cosmic quail is that a problem?

When I move far enough away and stare at an object, it starts to disappear, and that's fine, but when, not seeing an object in front of me because I'm too far away, I get the idea of ​​turning the camera to one side, I realize that I can still see it, and that's a problem.

tulip stag
#

Wahoooo it's working now!

#

Thanks yall

#

The calculation was based in years but two of the variables were using days. For some reason that made it output 0. Thanks for the tips on how to spot the broken variables >:)

#

While we're here, I've been gettin this Assertion failed on expression: 'IsInSyncWithParentSerializedObject()' UnityEditor.RetainedMode:UpdateSchedulers () ever since I attached the debugger. Should I worry?

grand snow
#

And if you ever need a real date time later if done manually you can easily produce invalid dates (e.g. manually changing the year +1 instead of adding 1 year)

tulip stag
#

I am using 365.25 for my variables, but I'll looking this up later!! Maybe it could save me some of my headache lol

naive pawn
#

did you miswrite a sign?

naive pawn
grand snow
#

C# has great date and timespan objects so use them!

dry cloak
lapis thorn
#

So like, im just starting Unity and C#. I am just wondering how would someone make a item skin system. I have the basic idea on how it works but how does a game remember. Does anyone know if there is a documention i could read?

tulip stag
naive pawn
tulip stag
#

But still, I'll take a look at this! Maybe I'm being stupid and these objects can help me out just the same

naive pawn
tulip stag
#

🤷‍♀️

dry cloak
tulip stag
#

Could go either way. Will hardly affect the results. I guess it feels nicer? 😭

grand snow
#

Then i guess you can take the simplified approach if it never needs to be real dates

jovial yacht
grand snow
#

Use a debugger, step through with the arg that causes the bad output and you will surely see what goes wrong 🦾 @tulip stag

#

and shouldnt you floor for your days to years check?

naive pawn
naive pawn
dry cloak
# naive pawn can you show how you're using `grounded`?
    public float playerHeight;
    public LayerMask WhatIsGround;
    public bool grounded;

  void Update()
  {
      grounded = Physics.Raycast(transform.position + Vector3.up * 0.1f, Vector3.down, playerHeight / 2, WhatIsGround);

      MyInput();
      SpeedControl();

      rb.linearDamping = grounded ? groundDrag : 0f;

      // Handle jumping
      if (Input.GetKey(jumpKey) && readyToJump && grounded)
      {
          readyToJump = false;
          Jump();
          Invoke(nameof(ResetJump), jumpCooldown);
      }
  }

#

The header is not right next to the Void update

i promise my code isnt that ugly

dry cloak
#

so i moved some stuff around, and fixed the locations of things, but now grounded doesnt check what so ever

strong wren
#

Are you sure playerHeight is big enough? Might want to draw the ray with Debug.DrawRay/DrawLine

dry cloak
#
        Debug.DrawRay(transform.position, Vector3.down * (playerHeight * 0.5f + 0.2f), rayColor);```

i tried using this but no raycast apeard
#

and what is wierd, is when i drag the player up the groundcheck activates

#

so i draged orieantation up which is where things are linked to

#

and now i can jump, but that doesnt fix my original problem of groundcheck not being true when sliding

waxen adder
#

"Sliding" do you mean like on a ramp? Sounds like it's because the ground check doesn't quite reach into the ground in that scenario

dry cloak
#

just in general. i hit C and i get a speed boots, and my charecter size gets smaller

#

imgaine like ultrikill sliding

waxen adder
#

Oh interesting, maybe it's because of the character size part

#

Can't say for certain, just kinda spitballing possible problem areas

dry cloak
#

would you like the sliding script?

waxen adder
#

Let me see the ground checking stuff first

dry cloak
#

i should proppably add some explinations for future help

#

and there is some left over chat gpt notes i gotta reomve too lol

waxen adder
#
grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, WhatIsGround);

Looking here right now. I don't quite remember, what is the 3rd parameter for?

#

Is that raycast length?

dry cloak
#

yes

waxen adder
#

Gotcha

dry cloak
#

it takes the hight of the player and halfs it

waxen adder
#

That really makes me think shrinking char size might do something

queen adder
#

can you guys listen to a begginer please?
My tank script doesn t work, because when i move backwards, it switches d with a and a with d. Forward is ok.

Here is the code : https://paste.myst.rs/en0k8alx

Here is how the gizmos are in local view:

waxen adder
#

Cause then the raycast is smaller in length

#

Depends on what happens to them. Can you show an image of the guy sliding?

dry cloak
#

Im still on bean stage sadly

#

i have the camera as a seperate entiy and its position is linked to oriantation to avoid jitter and lag

waxen adder
#

Interesting. My thought was, it was shrunk, but maybe floating or something

#

But that's not what happens here

#

How thick is the floor?

#

Actually that wouldn't matter nvm

dry cloak
#

ill link my slide script for you too

waxen adder
#

Try drawing a gizmo line that illustrates the raycast

dry cloak
#

like this? ```private void OnDrawGizmosSelected()
{
if (!Application.isPlaying) return;

Gizmos.color = grounded ? Color.green : Color.red;
Vector3 rayOrigin = transform.position;
float rayLength = playerHeight * 0.5f + 0.2f;

Gizmos.DrawLine(rayOrigin, rayOrigin + Vector3.down * rayLength);

}```

near thicket
#

How would I go about making a machine assembling bay? What I have in mind specifically is an area where players are able to take different game objects(each part will have specific attachment nodes).
I'm specifically asking about how I would get around making different gameobjects clip together, or detect which part is connected to what, etc

dry cloak
#

nothing is drawn

waxen adder
#

Even when standing?

dry cloak
#

yep

waxen adder
#

Also keep in mind with that function i'm pretty sure you need the object selected in the scene

dry cloak
#

it is

near thicket
waxen adder
# dry cloak it is

Ok, for testing purposes, slap a debug.log before the early return. Make sure it's actually getting called

dry cloak
waxen adder
#

ye

#

Now see when/if the message pops up

dry cloak
#

nothing

waxen adder
#

At all?

#

Even when selected?

dry cloak
#

yep

#

wtf

waxen adder
#

Welp, there's our major problem eh? XD

dry cloak
#

yep

waxen adder
#

Doesn't seem to be getting called

dry cloak
#

but i can stilll jump?

waxen adder
#

Lemme see, there's a gizmo function I like using. One sec

#

WAIT

#

I don't think your gizmos are toggled on

dry cloak
#

how do i do that?

waxen adder
#

I'll show you, one sec

dry cloak
#

also i took some vids of what it looks like from my end

waxen adder
#

The orb thing on the right