#💻┃code-beginner

1 messages · Page 331 of 1

fading trench
#

this line

astral falcon
#

so when you do NOT press the keys, like not touching the keyboard, the player flies up?

loud mango
#

uhhh ........ uhh

fathom locust
#

yepp

willow scroll
#

Simply using the GetKey(KeyCode) method

loud mango
#

for mobile

queen adder
#

i added a canvas with a slider, and it not appear on the gameplay screen, i new programmer, can anyone help me please?

loud mango
#

so i use a button

astral falcon
#

either use an UI button or get the new input system and use the touches input.

astral falcon
queen adder
deft grail
#

should find it really quickly, as the game window isnt big

willow scroll
# loud mango so i use a button

I don't think the UI Button has the events other than onClick. You, probably, gotta use the OnMouseDown / OnMouseUp methods.

#

Actually, you may want to implement your custom Button, which should be quite straightforward

queen adder
willow scroll
#

There's the Scale

queen adder
#

yea, what i should do?

fading trench
#

debug log your moveDir

fathom locust
#

ok I'll try

willow scroll
queen adder
#

but when i run the game the slider dont apear

willow scroll
#

Or disabling the slider

#

Please, show the slider on run time

queen adder
#

the slider do not apear on the run time, thats the problem xD

hardy wolf
#

hey all

#

would like to ask

#

how long would it take to code a Stamina bar?

willow scroll
willow scroll
queen adder
#

OK

#

sry caps

willow scroll
hardy wolf
#

Or is it a fast process?

queen adder
#

it follows the camera

hardy wolf
# willow scroll Using a `UI Scrollbar`, adjusted by the script, which has the `stamina` variable...

Looking at something like this

https://youtu.be/2OKReQ9HEzc

In this unity tutorial, you'll learn how to make an energy/stamina system. Energy/stamina systems are efficient mechanics to increase player retention, pace content, monetize a game.

Timestamps:
0:00 Intro
0:16 Energy UI Setup
2:05 Energy Scripting
10:15 Conclusion

#Hooson #Unity3D

Play my first mobile game: Bot Attack - 2D Top-down shooter
➤...

▶ Play video
queen adder
willow scroll
# hardy wolf I see, would it take many hours?
    1. Create a Scrollbar
    1. Create a script for your stamina if it's not created yet
    1. Add the stamina variable
    1. Add a reference to the Scrollbar
    1. Add a method to adjust the Scrollbar's value
      Takes 2 minutes for me, which is 0.033 if you need to know it in hours
maiden niche
#

Could someone help me with adding a new inventory system to my project. i already made the new inventory system its just that i dont know how to add it properly.

hardy wolf
willow scroll
hardy wolf
fading trench
willow scroll
queen adder
#

i so far away

willow scroll
queen adder
#

how i put it very very close

willow scroll
queen adder
#

yess

maiden niche
# fading trench what do you mean add it properly?

so i made my game (which already has a inventory system but its very bad) and then i made a inventory system thats good but i cant figure out how to implement it properly and some classes are overlapping and its confusing me very badly

queen adder
#

thank you for your patience

hardy wolf
#

Context: I was hiring a developer

willow scroll
hardy wolf
#

Okay no worries, just wanted a Game Developers POV, as I am afraid of being overcharged regarding this.

willow scroll
willow scroll
hardy wolf
#

I just wanted some insight haha

willow scroll
#

This depends on the level of the multiplayer.

hardy wolf
#

It's just a lobby that's in a Pixel Game.

willow scroll
#

But stamina system, which is, if what you say, just a simply stamina bar, doesn't really require too much work, as mentioned above

hardy wolf
#

Like a common server, like Habbo

willow scroll
#

Well, it really depends on the difficulty of the multiplayer

#

If it's hard enough, it could, probably, cost this much

hardy wolf
#

I see, if it's something like Habbo, like a simple one where people just walk and interact via trading, would it be difficult?

willow scroll
#

I don't know Habbo.

hardy wolf
#

I see, like a social Pixel game, I have the beta ready and I can share it with you here.

#

Can you enter into it? @willow scroll

#

What do you think?

maiden niche
#

do you also need the classes?

willow scroll
maiden niche
#

my old one needs to go and the new one should be added but the classes then get all mixed up

hardy wolf
willow scroll
willow scroll
hardy wolf
#

It's still in the early stages so it is not playable yet.

willow scroll
hardy wolf
willow scroll
#

And I 1.2k is definitely too much for the simple lobby

hardy wolf
willow scroll
#

But I'm not the one to judge UnityChanBugged

hardy wolf
stuck palm
#

How could I make a loading screen? Like a screen intermediary between 2 different screens where it says it's loading?

#

Two different scenes rather

willow scroll
maiden niche
#

no i want to know how to implement the new one

#

i always get stuck bcs of variables that change and classes that overlap

willow scroll
#

Simply name the variables the way that doesn't confuse you

#

And don't have a few different methods, all called Add or Remove

maiden niche
#

they are not confusing but the problem is for example in the old toolclass you dont have an enum but in the new one you do but then that doesnt work anymore

maiden niche
#

ye it doesnt show up anymore even though i have the same code in a different project

#

and there it does work

willow scroll
#

Why would you have the same code in a different project?

maiden niche
#

its just a samplescene project for making the new inventory

willow scroll
#

I mean, I don't know how to help you, as this doesn't look like a specific issue

maiden niche
#

ok np

small mantle
#

Is there a simple way to connect a float to a animation? I want an animation length for attacking to be the amount of attackSp. This attackSp will change often, so how would I go about making sure that the animation matches that attackSp length?

wintry quarry
small mantle
queen adder
#

why is my bool changing states from false to true when scenes are changed?

wintry quarry
#

You'd have to show us what you mean

#

But, values don't change themselves

#

You might be getting confused by a different copy of the script existing in the new scene

gentle condor
#

@small mantle you can add a parameter to your animator controller with AttackSpeed or something similar, and in your attack state, use that parameter as a speed modifier.

queen adder
# wintry quarry You'd have to show us what you mean

so i have this game manager with this method that is used for a button to switch states, the bool isOn is checked by another script to wether do something or not public void toggleSpeech() { if (isOn) { isOn = false; } else { isOn = true; } }

wintry quarry
#

In a paste site

queen adder
#

can u send a link for a paste site 😄

wintry quarry
#

Also you can just do isOn = !isOn;

#

!code

eternal falconBOT
queen adder
#

its a simple manager code just for a ui project

#

its at the last method

wintry quarry
#

Everything in the old scene will be destroyed

queen adder
#

right so i have to use dontdestroyonload?

wintry quarry
#

If you want it to survive between scene reloads yes

#

Look up the Singleton pattern

queen adder
#

right imma go learn that since i never have yet

queen adder
shell ice
#

hello everyone , i have a gameobject and i want to create an animation where i move it around the scene ( i did it with the keyframes )

#

i wanted the animation to be relative to where the object is currently at

#

but it just always goes back the the position where i animated it in the window

#

any idea on how to do this

strong wren
shell ice
#

it worked

#

thank you

gilded kiln
#

A specific script has a maximal gameObject limit ? Bcs I want to activate a gameObject with SetActive(true) the condition works i test it with a debug.log but just Unity doesn't want to activate the GameObject

#
if (isAttacking == true)
    {
        if (spriteRenderer.flipX == false)
        {
            glowAttackEffectright.SetActive(true);
            Debug.Log("glow right activate");
        }
        else
        {
            glowAttackEffectleft.SetActive(true);
        }
    }```
wintry quarry
#

If that log did print, add more logs to every place where you call SetActive.

#

YOu're probably deactivating the object elsewhre

gilded kiln
wintry quarry
#

Yeah but i'm not sure what the question means. Kind of like if you said "Does your dog have a maximal grocery store limit?"

wintry quarry
gilded kiln
wintry quarry
#

I just want to see a screenshot of the unity editor with the console window visible

#

and the full script

gilded kiln
wintry quarry
#

Why you lie to me

#
    if(!isAttacking){
        rightSide.SetActive(false);
        leftSide.SetActive(false);
    }```
gilded kiln
#

these gameObjects works perfectly

#

but the other idk why but not

wintry quarry
#

Because look at which objects you assigned

gilded kiln
#

I want to cry

#

bro you save me 💀

#

my mental health want to mercy you

#

I'm so dumb sorry to spend your time thx you

main karma
#

how would one go about checking if the collision on the capsule cast is at the top or at the bottom of the capsule (floor or ceiling, not walls) ? (because I want a different script to be checking for wall collision)

summer stump
wraith valley
#

Hello, the character is not jumping, please help.

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

public class PlayerController : MonoBehaviour
{
    public float speed = 10f;
    public float velocity = 100f;
    private Rigidbody2D rb2;
    public float jumpForce = 10f;

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

    void Update()
    {
        float horizontal = Input.GetAxis("Horizontal");
        transform.position += Vector3.right * horizontal * speed * Time.deltaTime;

        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            Jump();
        }
    }

    void Jump()
    {
        RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up, 0.1f);
        Debug.DrawRay(transform.position, -Vector2.up, Color.green, 0.1f);

        if (hit.collider.CompareTag("Ground"))
        {
            rb2.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
        }
    }
}
summer stump
#

Also check if the y value of the hit point is above or below the center

slender nymph
main karma
#

one more question however, what if there's 2 hits one on the side and on the bottom for example

#

can I cycle between the objects that come in contact w the capsule?

summer stump
#

Well, not all overrides give you the RaycastHit, so you would have to ise one of those

main karma
#

if so that would solve all my problems

wraith valley
slender nymph
#

it shouldn't have

summer stump
main karma
#

great

slender nymph
summer stump
#

Pretty sure that capsulecast, like raycast, just returns the first hit only

#

So using capsulecastall WOULD allow you to iterate the collider array it returns

main karma
#

ah makes sense

#

thank you very much

wraith valley
main karma
#

I need to optimize my hit detection cuz I use like 2 capsules and 4 raycasts to check for collision and that consumes a lot of resources for no reason, which is why I asked

slender nymph
wintry quarry
wraith valley
slender nymph
#

wdym what? transform.Translate is doing exactly what you were doing before
so nothing has meaningfully changed

polar acorn
wraith valley
polar acorn
#

What are you expecting this to change?

main karma
#

well I also use portals that use cameras to render plenty of stuff at the same time so I try to save up where I can, also the collision system I got going on doesn't account for when the character stays still and objects move toward it so it just passes right through unless I press a key to move right b4 impact

wraith valley
#

The character can`t jumping

slender nymph
#

i've already told you why

polar acorn
#

You've been answered on what to do to fix that

polar acorn
slender nymph
#

proof for the "raycasts are basically free" claim: #💻┃code-beginner message
of course this was a test with no physics objects in the scene so i'm not sure if that would impact the performance. but doing 1000 took half a millisecond

main karma
#

also one last question, do events consume performance? like if I have an event going on every 0.1 seconds?

slender nymph
#

it's the work you do in the methods subscribed to the events that actually matter

wraith valley
slender nymph
slender nymph
#

do you know how to read?

slender nymph
#

what about that do you not understand?

wraith valley
#

This move either via the transform or via physics. doing both is going to lead to issues.

slender nymph
#

you need to move either by modifying the transform or by using physics. do not do both.
moving using transform.position or transform.Translate is obviously modifying the transform. using the rigidbody to add force or assign velocity is moving using physics.

fluid haven
#

how can i save a .txt file, that all players canm access?

main karma
#

I just want to make sure this isn't a bad approach or anything

slender nymph
main karma
#

thank you

wraith valley
slender nymph
#

well that doesn't actually perform a move, but it's at least on the right track

wintry quarry
#

just host a text file on your web server somewhere

fluid haven
wintry quarry
#

Cloud save is to save per-user save files

#

that are private to that user

#

it's not for "public" text files or whatever your use case seems to be

#

What kind of data are you trying to save here? A high score list or something?

fluid haven
slender nymph
#

why use a game engine for that? 🤔

wintry quarry
#

Yeah what haha

queen adder
#

Hello everyone...I am still new to unity and I am having an issue, the editor status show that I am getting 600FPS in the game menu...but VERY stuttering and unplayable...(despite it's being just a plane ground and a cube with an fps player)

wraith valley
wintry quarry
fluid haven
slender nymph
slender nymph
wraith valley
queen adder
# wintry quarry Your code is probably doing something wrong. like multiplying deltaTime into mou...

my code you say?

using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public Transform MainCamera;
    public float Sensitivity = 5.0f;
    private float yaw;
    private float pitch;
    private float Xrotation;

    public float speed = 1.0f;
    private float horizontalInput;
    private float forwardInput;
    private float sprintInput;
    void Start() {
        Cursor.lockState = CursorLockMode.Locked;
    }

    void FixedUpdate(){
        yaw += Input.GetAxisRaw("Mouse X") * Sensitivity;
        pitch = Mathf.Clamp(pitch, -90f, 90f);

        pitch -= Input.GetAxisRaw("Mouse Y") * Sensitivity;

        transform.localRotation = Quaternion.Euler(0, yaw, 0);
        MainCamera.localRotation = Quaternion.Euler(pitch, 0, 0);
        
        
    }
    void Update()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        forwardInput = Input.GetAxis("Vertical");
        transform.Translate(Vector3.forward * speed * forwardInput * Time.deltaTime);
        transform.Translate(Vector3.right * speed * horizontalInput* Time.deltaTime);
    }
} ```
#

"sorry"

wintry quarry
#

so of course it will look stuttery

#

Why are you using FixedUpdate

fluid haven
queen adder
slender nymph
queen adder
wintry quarry
#

literally just move your code into Update

fluid haven
queen adder
wintry quarry
#

mouse input is framerate independent already. It doesn't need deltaTime

slender nymph
queen adder
#

WHAAAAAAAA
been stuck on this for 2 days!
man unity is not for me @-@

queen adder
#

for now on...FixedUpdate is an enemy

wintry quarry
#

it's not an enemy

#

you just need to understand what it's for

#

mainly physics

queen adder
wintry quarry
wintry quarry
#

because it's completely ignoring the physics engine

#

and just teleporting your character around

#

it's not going to respect collisions and gravity etc properly

queen adder
queen adder
stoic glen
#

Why cant I edit the second Collider and how can I use it only as a trigger and not a collider

wintry quarry
stoic glen
wintry quarry
#

but maybe because it's a prefab override

stoic glen
#

I can use this Button, kinda weird

stoic glen
stoic glen
wintry quarry
#

that's not "working like a normal box collider"

#

normal box colliders physically collide with other colliders

wintry quarry
#

but it's usually better to just put the collider on a different layer and use a layermask.

stoic glen
#

Can it be a problem if a create a layer below UI

#

Because I never used Layermasks

wintry quarry
#

I don't understand what you are asking

#

UI is not relevant to our discussion

stoic glen
#

I mean, should it be between the predefined or can it be below UI

wintry quarry
#

It doesn't matter at all

stoic glen
#

Ok perfect

patent compass
#

Hello, does anyone know why my camera is not moving when I drag my mouse.

    [SerializeField] private Camera cam;

    private Vector3 dragOrigin;
    private void Update(){
        PanCamera();
    }

    private void PanCamera(){
        if (Input.GetMouseButtonDown(0)){
            dragOrigin = cam.ScreenToWorldPoint(Input.mousePosition);
        }

        if (Input.GetMouseButton(0)){
            Vector3 difference = dragOrigin - cam.ScreenToWorldPoint(Input.mousePosition);

            Debug.Log("origin " + dragOrigin + "newPosition " + cam.ScreenToWorldPoint(Input.mousePosition) + "= difference " + difference);
            cam.transform.position += difference;
        }
    }```
wintry quarry
#

Is it logging any difference?

patent compass
wintry quarry
#

and you're not passing in a z distance

#

so you're just getting the camera's position out

#

you should probably use Plane.Raycast with ScreenPointToRay instead

dusty nimbus
#

Hoy all! Just trying to figure out here why a world object with a canvas attached using world space is being physically blocked by being visible by a UI Canvas using Screen Space - Overlay UnityChanThink

patent compass
wintry quarry
dusty nimbus
hollow dawn
#

I have this asset that im using and I was wondering if I could get the thirdperson prefab and make it into first person would this be possible? https://assetstore.unity.com/packages/essentials/starter-assets-character-controllers-urp-267961

Get the Starter Assets: Character Controllers | URP package from Unity Technologies and speed up your game development process. Find this & other Essentials options on the Unity Asset Store.

timber tide
#

there is a first person template

hollow dawn
timber tide
#

Ah, well, anything is possible if you put the time into it

chrome tide
#

I have a script SoundsEmitter. It's attached to every object that emitts some kind of sound. This one is meant to be attached to the player:

using System;
using UnityEngine;

public class SoundsEmitter : MonoBehaviour
{
    public int[] emittedAudio = new int[2];
    public PlayerMovement playerMovement;

    private void Update()
    {
        AudioChange();
    }
    private void AudioChange()
    {
        switch (playerMovement.state)
        {
            case PlayerMovement.PlayerStates.Standing:
                emittedAudio[0] = (int)SoundsManager.SoundVolumes.Standing;
                emittedAudio[1] = (int)SoundsManager.SoundDistances.Standing;
                break;
            case PlayerMovement.PlayerStates.Walking:
                emittedAudio[0] = (int)SoundsManager.SoundVolumes.Walking;
                emittedAudio[1] = (int)SoundsManager.SoundDistances.Walking;
                break;
            case PlayerMovement.PlayerStates.Running:
                emittedAudio[0] = (int)SoundsManager.SoundVolumes.Running;
                emittedAudio[1] = (int)SoundsManager.SoundDistances.Running;
                break;
        }
    }
}```
Now i also want to attach this script to a Bell which makes sound once interacted with, but I don't want to create a completely new script just to change 1 thing (removing the playerMovement variable in this case). Is it possible to edit this script without creating an entirely new one?
stark ruin
#

Hi guys,i am having a problem with an object,i want to make it rotate but it starts to rotate if i give him a lot of rotational force,how can i decrease it
the friction is set to 0

rocky canyon
rocky canyon
stark ruin
#

It is like i have to give it so much rotational force

#

cause i tryed via script

chrome tide
# rocky canyon singleton audiomanager sounds like a solution

so its better if i keep this script and define every sound emitting object inside of it? the problem is that this script has to be attached to the sound source, because i have an entity that checks all the gameobjects that have a SoundEmitter component.

rocky canyon
#

drag = air resistance
angular drag = rotational resistence

wintry quarry
stark ruin
rocky canyon
#

sounds good if its working

stark ruin
#

Yea but it doesn’t work

chrome tide
stark ruin
rocky canyon
#

whats that mean? play "spot the difference"

wintry quarry
rocky canyon
#

one must not be like the other.. and the reason behind differences

chrome tide
wintry quarry
chrome tide
#

How do i identify scripts with tags? I have multiple scripts that manage sound emitting, but each object has a different name of the script. for an example: player has a PlayerSoundEmitter script, while a bell has a BellSoundEmitter script. but these scripts all do the same thing: they manage sound, and each one of them has a emittedAudio[] float array. i can't attach a tag to the script, so how do i identify them?

rocky canyon
#

if they all have different names why use tags?

#

can search for the component directly

queen adder
rocky canyon
#

the only reason u'd use tags in that situation is if the scripts were named the same and u were trying to differientiate

queen adder
#

If ur looking for a specific script you just look for those types

#

I cannot believe i forgot the syntax for this

rich adder
#

FindObjectOfType

slender nymph
rocky canyon
#

FindObjectOfType

queen adder
#

Thank u lmao

rocky canyon
#

in Unity6 its deprecated tho

rich adder
#

yeah deprecated but still works

rocky canyon
#

true.. just pointing it out

queen adder
rocky canyon
#

ive switched to FindFirst

queen adder
#

IPlaySound

chrome tide
chrome tide
queen adder
#

And you can just call there PlaySound Interface methods that way u dont have to worry about the specific script. If all ur really worried about is them playing a sound

wintry quarry
slender nymph
wintry quarry
#

If all they're really doing is holding an audio clip and playing a sound when desired, it seems like this script doesn't do much more than what an AudioSource already does.

#

In that case you should delete the script entirely and just use AudioSource directly

chrome tide
# wintry quarry If all they're really doing is holding an audio clip and playing a sound when de...

these scripts aren't playing audio, it just defines the loudness of the sound it is generating. for an example: when the player state is PlayerStates.Standing the volume is 0, when it's PlayerStates.Walking the volume i 3 etc. it wont play audio, it just stores the volume and range of the audio. i have the volumes and ranges defined in enums:

public enum SoundVolumes
{
    Standing = 0,
    Walking = 3,
    Running = 5
}
public enum SoundDistances
{
    Standing = 0,
    Walking = 10,
    Running = 20
}```
wintry quarry
#

What does the script do when it's NOT being used for player movement

#

What does it do for a bell?

#

maybe sharing the code for this script would be a bit more illuminating

chrome tide
# wintry quarry What does it do for a bell?

i didn't implement the bell yet, but the whole project i'm creating has a monster that reacts to sounds so it checks every gameobject with a script that manages the audio loudness, it checks the volume of all the scripts and checks which script has the loudest volume. then it sets the agent.setdestination() to the gameobject that has the script.

wintry quarry
#

it definitely shouldn't know or care about player movement concepts like walking/running/etc.

chrome tide
wintry quarry
#

The bell script can be like:

[RequireComponent(typeof(NoiseMaker))]
public class Bell : MonoBehaviour {
  public float BellVolume;
  public float BellRange;

  IEnumerator RingBell() {
    GetComponent<NoiseMaker>().volume = BellVolume;
    yield return new WaitForSeconds(5); // ring for 5 seconds
    GetComponent<NoiseMaker>().volume = 0;
  }
}```
molten dock
#

should I worry about code efficiency in a 2D game

wintry quarry
#

just as a simple example

chrome tide
#

Thanks for the examples praetor

wintry quarry
molten dock
#

Very fast typer

wintry quarry
rocky canyon
#

im a simple man..
using UnityEngine;

public class AudioManager : MonoBehaviour
{
    public static AudioManager Instance;
    AudioSource source;

    private void Awake()
    {
        if(Instance == null) Instance = this;
        else Destroy(this.gameObject);

        source = GetComponent<AudioSource>();
    }

    public void PlayClip(AudioClip clip, float volume)
    {
        source.volume = volume;
        source.clip = clip;
        source.Stop();
        source.Play();
    }
}

i use singletons for all my audio (for the most part)

#

but i get that its not always the best way

molten dock
#

so is singleton the name for static variables

rich adder
#

singleton means only 1 exists

rocky canyon
#

its a single instance of a class

molten dock
#

Oh alright

rocky canyon
#

but that means you can access it anywhere..

#

b/c theres only 1

#

no conflicts

rocky canyon
#

but.. i haven't figured out the best way to define a singleton just yet..

#

im working on it 😅 .. i have soo many different versions.. all a bit different

#

heres what i plan on adopting everywhere soon enough

rocky canyon
#

i added one just incase 😄

strong token
rocky canyon
#
using UnityEngine;
public class AudioManager : Singleton<AudioManager>
{
    AudioSource source;
    protected override void DoAwake()
    { source = GetComponent<AudioSource>(); }
}```
#

i went ahead and changed it over to use the generic singleton

rocky canyon
#

and from my understanding, i agree, Destroy happens at the end of the frame.. it gathers it all up.. and destroys it all at once

#

theres DestroyImmediate() but i think thats more for editor stuff

brittle isle
#

So I'm using rigidbodies for my enemies and player in my 2d platformer, and even if I tinker with the collision grid, they can push each other. Any way to prevent this? https://hatebin.com/wwftbgdakf

stuck palm
#
private void OnTriggerEnter(Collider other)
    {
        HandleExplosion();
    }

    protected virtual void HandleExplosion()
    {
        
    }

if something inherits this class, does ontriggerenter still happen and will handleexplosion fire?

slender nymph
#

yes

#

but also tryitandsee

wintry quarry
paper sable
#

the -2 below the 0 should dissapear after a second but it doesn't, can anyone help me please? this code makes the text appear and dissapear

public IEnumerator ShowScoreAddText(int multiplier)
    {
        GameManager.scoreAddText.gameObject.SetActive(true);

        GameManager.scoreAddText.SetText(multiplier > 0 ? $"+{scoreAddon}" : $"-{scoreAddon}");

        yield return new WaitForSeconds(1f);

        GameManager.scoreAddText.gameObject.SetActive(false);
    }
paper sable
#
void Update()
    {
        if (transform.position.y < -5)
        {
            if (GameManager.score <= scoreAddon) GameManager.score = 0;
            else if (GameManager.score > scoreAddon) GameManager.score -= scoreAddon;

            StartCoroutine(ShowScoreAddText(-1));

            Destroy(gameObject);
        }

        transform.Translate(0, -speed / 100, 0);
    }

    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.CompareTag("PlayerTop"))
        {
            GameManager.score += scoreAddon;
            StartCoroutine(ShowScoreAddText(1));
            Destroy(gameObject);
        }
    }```
wintry quarry
#

the coroutine will stop when you do that

#

you can't run a coroutine on an object that has been destroyed.

paper sable
wintry quarry
#

it happens immediately

#
            StartCoroutine(ShowScoreAddText(-1));

            Destroy(gameObject);```
#

you start the coroutine

#

then you immediately destroy the object

paper sable
#

should i destroy the object in the coroutine?

wintry quarry
#

the whole point of the coroutine is that your code doesn't wait until it ends

wintry quarry
paper sable
#

thanks

rocky canyon
#

calling a coroutine is like telling it to go ahead and run..
then the code moves along..

stoic glen
#

if(hitInfo.collider.gameObject.layer == 6)
Why does this line take so long to execute?

rocky canyon
#

idk, it shouldn't.. really it would depend on the complexity of ur scene.. or hiearchy..
it could involve traversing through a significant number of GameObjects and/or components which could be where the delay is

stoic glen
#

The following code is stuttering, but the fps doesnt drop

rocky canyon
#

if ur collision matrix is also configured in a way there are many layers with specific interactions it might also might make it where it has to do additional checks to determin the layer of the coliders gameobject

#

how did you come to conclusion its that line thats causing it?

#

if the fps doesn't drop.. its probably not a performance issue

stoic glen
#

in the following code, an object is moved to the position of the raycast, which only runs very slowly. If I change the code to e.g. false/true, the object is moved smoothly.

#

I'm really confused, because this doesnt require a lot of process power or a lot of data

#

It feels like a grid is created and the object can only be moved into the next cell

rocky canyon
#

is it not your code? are u using a third party codebase or something?

stoic glen
rocky canyon
#

id say go ahead and profile it..

#

i dont see anything specifically

stoic glen
rocky canyon
#

look for big spikes.. when you come across one pause the game/profiler and select the spike..

#

you can go thru the heirarchy and find what in the code is causing issues

stoic glen
#

Ok, I try to search for the problem thx for your help

shell ice
#

i get stuck on this screen for no reason

#

my project isnt even that big

#

any idea ?

summer stump
# shell ice

It happened when you hit play?
Likely infinite loop

rocky canyon
#

^ try restarting.. if that doesn't help its probably a loop

round arch
#

how would i make a collision between a box collider and a rigidbody work at fast speeds? my box collider is a moving platform but when i move it faster the rigidbody falls straight through

rich adder
round arch
#

i have tried that, still falls through...

rich adder
#

you're likely not moving with physics

round arch
#

does moving a platform in the editor not effect physics?

rich adder
#

not if you're moving the transform alone

round arch
#

ah

rich adder
#

it will affect it but not accurate

round arch
#

right, and to effect it with physics i need to script that?

rich adder
#

you need to move the Rigidbody itself with its own methods

#

like AddForce, Velocity etc.

round arch
#

i wanna explain what im trying to achieve, i have a platform that will be able to move to lauch the player, do i add a rigidbody to the platform so i can add force and just disable gravity on it?

rich adder
#

if it only has to push player you can AddForce sure

#

you can also make it Kinematic and do MovePosition

round arch
#

sweet, thanks for the help!

lavish jolt
#

Hi. I have a problem. I have bullet holes made by decal projector and if I shoot in the surface at a high angle the decal is stretching very much. How can I fix it?

        protected void SpawnDecal(RaycastHit hit, Vector3 direction)
        {
            GameObject decal = decalsPool.Get();
            float positionMultiplier = .1f;
            Vector3 multipliedDirection = direction * positionMultiplier;
            Vector3 spawnPosition = new Vector3(hit.point.x, hit.point.y, hit.point.z) -
                                    new Vector3(multipliedDirection.x, multipliedDirection.y, multipliedDirection.z);

            
            decal.transform.position = spawnPosition;
            
            decal.transform.rotation = Quaternion.LookRotation(direction);
        }
        public override void Shoot()
        {
            animator.SetTrigger("Shoot");
            audioSource.pitch = Random.Range(0.9f, 1.1f);
            audioSource.PlayOneShot(weaponSO.shootSound);
            fireEffect.Play();
            if (Physics.Raycast(mainCamera.transform.position, mainCamera.transform.forward, out RaycastHit hit,
                    weaponSO.range))
            {
                
                SpawnDecal(hit, mainCamera.transform.forward);
            }
        }
kindred nest
#

you're displaying it at an angle of it being shot regardless of how sharp that angle is, so you could see what values you get from the "mainCamera.transform.forward" once the decals look off and simply clamp it below and above the undesired values

#

unless you want them to not stretch at all then I'm sure there is a simple way to just spawn decals with the default normal at a given contact point, but didn't ever use decals just deducting from the code

rocky canyon
#

ya, just rotate it to match the hits' normal

wintry quarry
#

or -hit.normal

#

one of those two

kindred nest
#

or clamp it if you want some stretching up to a point

wintry quarry
#

Also why new Vector3(hit.point.x, hit.point.y, hit.point.z) instead of just hit.point??
same with new Vector3(multipliedDirection.x, multipliedDirection.y, multipliedDirection.z);??

kindred nest
#

one does not question code that does the job

wintry quarry
#

yes one does

rocky canyon
#

is this ugly?

willow scroll
kindred nest
#

I have no freaking clue what I'm looking at

rocky canyon
#

thats harsh

wintry quarry
# rocky canyon

could be worse... just put it in a function and forget about it 🙂

willow scroll
#

please, use a switch

rocky canyon
#

i had a switch statement originally..

kindred nest
#

this looks like a nice switch use-case

#

get it

#

use case

rocky canyon
#

well its better than this

kindred nest
#

not sure about speed between the two, but nesting this much ternary operators is never gonna be more readable/maintanable than the switch. Sure, you saved 15 lines, but try changing anything in it, or getting to the bottom of a bug in the middle of it

#

your call, you might never have to go back to it, so enjoy it working and don't worry about it

rocky canyon
#

ya, i havent checked the speed yet.. but my guess is its negligible

#

ya, i dont think imma ever have to modify it.. its just converting Cardinal directions to vectors

kindred nest
#

I see some examples of pattern matching for switch statements in C# posted on the web:

var operation = 2;

var result = operation switch
{
    1 => "Case 1",
    2 => "Case 2",
    3 => "Case 3",
    4 => "Case 4",
    _ => "No case availabe"
};

Console.WriteLine(result);

didn't have the opportunity to try them tho. Might be nice for what you try to achieve

short goblet
#

Good evening everyone! I started programming on Unity a little over a week ago, and I ran into what you might call a bug: when the character jumps, it moves in a direction not respecting the Vector3.up. I've been trying to figure out what causes it for days, but I've lost hope now. Here I attach the code. Thank you https://hastebin.com/share/uhomacexuv.csharp (If you see there's the function Jump() and MyInput(), i don't think the problem is in another position)

wintry quarry
# rocky canyon well its better than this

I'd probably do this:

Dictionary<Direction, Vector3> dirMap = new() {
  {Direction.North, Vector3.forward},
  {Direction.West, Vector3.left},
  // etc...
};

public Vector3 GetDir(Direction dir, Space space) {
  Vector3 result = dirMap[dir];
  if (space == Space.Local) {
    result = transform.TransformDirection(result);
  }

  return result;
}```
rocky canyon
#

never used a dictionary yet

#

perfect timing

wind raptor
#

Is there a way to change the font (or force monospacing of the default font) of the Text Input box in the inspector?

wind raptor
#

The black screen is text mesh pro text

rocky canyon
#

Vector3.up is global up.. it doesn't matter which way ur RB is rotated

#

transform.up is the local up

short goblet
#

Yeah, i know this

rocky canyon
#

well in the video its always moving up

short goblet
#

If you see I'm going backwords

rocky canyon
#

ohh, i thought ur issue was with the jump

short goblet
#

Even if in the code is only mentioned vector3.up

rich adder
#

btw dont do * Time.deltaTime; on mouse input

#

Mouse input is already Time Frame Independent

wintry quarry
#
   void MovePlayer()
    {
        moveDirection = orientation.forward * y + orientation.right * x;

        if (OnSlope() && !exitingSlope)
        {
            rb.AddForce(GetSlopeMoveDirection() * moveSpeed * 10f, ForceMode.Force);
        }

        if (isGrounded)
        {
            rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
        }
        else if (!isGrounded)
        {
            rb.AddForce(moveDirection.normalized * moveSpeed * airMultiplier * 10f, ForceMode.Force);
        }
    }```
rocky canyon
#

i know.. i seen that too

#

he's also setting rb.velocity in several places as well

#

ignoring the current momentum

short goblet
rich adder
#

no worries just a unity quirk 🙂

#

but yeah also rb.velocity is overriding anything you do with AddForce

rocky canyon
#

it'd be helpful not having to worry about the rigidbody rotating all over the place..

rich adder
#

its for slope correction it seems though? should be fine maybe

rocky canyon
#

most times people will rotate the player (root) gameobject on its lateral directions
and rotate a parented child Camera.. vertically

#

seperating the two rotations

rocky canyon
#

then why is ur capsule leaning like its drunk?

short goblet
rocky canyon
#

ahh, okie doke

glad rune
#

how would i add an intiger to the UnlSkins in line 15?

rich adder
#

OnSlope should probably be returning the corrected Velocity insted of being if statement.

short goblet
#

just it, it doesn't have anything functional, but with or without the rotation the problem remain. It seems like there's a strange line that's messing up the movedirection

slender nymph
short goblet
#

but i don't have any idea where, this strange direction seems only picking the jumping from the ground (isGrounded) and not when the character is OnSlope or in Air

rich adder
#

yeah I just use premade controllers UnityChanLOL

rocky canyon
short goblet
rich adder
#

yeah dealing with RB based controllers is tricky

rocky canyon
short goblet
short goblet
rocky canyon
short goblet
#

when i will learn pretty well the part of movements i will give myself the permission to use premade code

jovial sable
#

Hello, I was wondering if yall know how to make it so i collide with something once it enables a gameobject, but if i collide with it again it enables a different game object?

rocky canyon
#

could do that with a boolean or a counter

wintry quarry
#

and some if statements

short goblet
rich adder
rocky canyon
#

ya, i used this one heavily to learn how to code my character controller

#

lots of good stuff hidden away in that tutorial playlist

short goblet
#

so, anyone have any idea of where this problem come from?

rocky canyon
#

the only thing i can see.. is when u jump u set ur velocity directly..

#

thats going to cancel out any forces ur already applying to it

short goblet
rocky canyon
#

theres an alternative..

#

pass its velocity back in to itself.. on the X and Z

#

and only change the Y for the jump

#

rb.velocity = new Vector3(rb.velocity.x, [yourcustomY], rb.velocity.z);

#

something like that ^

#

that way ur not setting em to 0

#

like u are now.

#

b/c as of now.. ur setting the X and Z to 0 when u jump

short goblet
#

Okk, i'm trying it right now

#

I'll let you know in like 5 minutes

stuck palm
#

why is this if statement producing a NRE

  protected override void OnTriggerEnter(Collider other)
    {
        print("BOOMERANG HIT SOMETHING: " + other.name);
        if (other.TryGetComponent(out Character player) || other.transform.parent.TryGetComponent(out player))
rocky canyon
#

but thats just (1) thing i noticed.. it probably isnt going to fix the main problem..

wintry quarry
short goblet
#

i just used an addForce

slender nymph
rocky canyon
#

heck yea

short goblet
#

and not change the velocity

stuck palm
short goblet
#

thank you so much and sorry, i'm noob asf and i thinki will kill myself ❤️

rocky canyon
#

no worries.. we all had to learn too

wintry quarry
slender nymph
wintry quarry
jovial sable
#

are there jobs in c#?

wintry quarry
#

Of course

rocky canyon
#

nope..

wintry quarry
#

Or do you mean the job system

#

That's a Unity thing

jovial sable
#

no like employment

wintry quarry
#

of course

rocky canyon
#

no jobs anywhere..

#

lol.. ofc theres job 🤣

jovial sable
#

ima do smth like that when im older

rocky canyon
#

you should learn more than just c# tho..

#

ur best route is to know many different languages

rich adder
#

gpt7 no more coders left /s

jovial sable
#

like python or smth

#

ah

stuck palm
rocky canyon
#

python, java, c#, cpp, c

jovial sable
#

jeez

rocky canyon
#

im learning cpp and c atm.. b/c alot of electronics (microprocessors/controllers) use c and cpp

jovial sable
#

unreal engine uses cpp right

#

and visual

rocky canyon
#

yes it does..

rich adder
#

and verse

jovial sable
#

cool

rocky canyon
#

but any Unreal i've done, its all been visual

#

you dont even have to touch cpp for most things in Unreal

#

its like a FPS generator.. everything has presets and wizards

jovial sable
#

i see

#

im just gonna try to get good a c# for now but thats something for in the future

jovial sable
#

thanks i appreciate it

quick fractal
#

How would i go about using an IsTrigger collider to detect anything with the "Enemy" layer selected? I know how to detect collision from specific layers in theory but it's never worked for me.

#

Not sure if this is more fit for #archived-code-general but i have hardly any idea what i'm doing and started 7 hours ago

rich adder
#

a quick google search should tell you which one you need

#

also you should configure you ide

quick fractal
#

ide?

rich adder
#

the code editor

quick fractal
#

What exactly should i configure?

rich adder
#

!ide follow the instructions here in bot message for VS

eternal falconBOT
quick fractal
slender nymph
#

not collisions, but trigger overlaps. otherwise yes. Also use CompareTag rather than string equality to check the tag of an object

rich adder
#

the method is correct, the signature is wrong

slender nymph
#

oh wait, wrong paramter type lol

quick fractal
rich adder
#

the parameters of a method

#

if you're looking at the documentation you will see which part on the method doesn't match

quick fractal
#

The documentation has this, unless I'm not seeing it, all it does is change the speed when it enters

rocky canyon
rich adder
rocky canyon
#

you might wanna look again

rich adder
#

not inside the method itself

#

look at image spawncamp sent

quick fractal
#

Okay i can't say the word "O" for some reason, but my bad

rocky canyon
#

Collider vs Collision

quick fractal
#

Yeah...

rocky canyon
#

c# is a very picky language

#

punctuation, capitalization, all that matter

quick fractal
#

Alright i think it looks good now

#

Nope, compile error

rocky canyon
#

and another thing.. get in a habit of using .CompareTag("TagName");

#

its better than .tag

slender nymph
eternal falconBOT
rocky canyon
#

u use that to compare..

#

not the type..

#

sooo.. it wouldnt be if(collision.. anymore

#

it'd be if(other...

quick fractal
#

Sorry to be annoying everyone, I'm not normally i swear

rich adder
#

close vs, try Regen project files inside external tools in unity page, then open script again

quick fractal
slender nymph
slender nymph
#

let it finish loading first

quick fractal
#

Where does it say it's loading?

slender nymph
#

well it doesn't show Miscellaneous Files or the Assembly-CSharp in the solution dropdown at the top so that indicates it hasn't finished loading

#

you also conveniently cut off the bottom of the window where you would see the loading icon

quick fractal
#

It looks.. different

slender nymph
#

yes because it is correctly configured now

quick fractal
#

I cut off the bottom cause it has info i don't want on discord

#

Sweet, now i have to figure out why the red squiggly lines are there, thanks for helping with that

slender nymph
#

because you spelled it wrong

#

and you terminated the statement with ; instead of ) to close the if statement

quick fractal
#

Thanks 😅

rocky canyon
#

now it knows its a C# script.. and will start highlighting errors in your syntax

#

and CompareTag

quick fractal
#

If i had more than one IsTrigger capsule collider on the same gameobject along with my script, would it detect them all as the "same" collider or would i have to specify something

#

Oh damn it destroyed the gameobject like it should.. That's sick

rocky canyon
#

🤯 lol

polar acorn
quick fractal
# rocky canyon 🤯 lol

Do you happen to have any docs on setting up rudimentary health values for enemies & the player? I haven't been able to find any but now that you've all helped me figure out how i'm going to do damage i think that's gonna help immensely

#

Not that i have any enemies with a navmesh agent yet

patent patio
#

Hello 👋 I'm trying to set up URP and the Shader Graph.
When adding my URP Asset (with Universal Renderer) it breaks all of my textures (they turn magenta) and I get a missing reference exception camera error. Does anyone know what I might be doing wrong. For reference I am running 2022.3.13f1.

rocky canyon
#

it kinda has something about that.. I toggle a bool in another script ... but u can just as well change a variable..

#

or call a method that changes that variable..

#

and passing in a float or int

quick fractal
#

I would imagine i have to define different damage values from different attack types and then subtract that from the health pool

slender nymph
patent patio
slender nymph
#

then share screenshots of your materials in the correct channel and ask for help there

patent patio
#

Alright, my apologies.

fathom prism
#

Hello

#

Anyone know how do I rotate an object like it rotates using the rotate tool

polar acorn
#

transform.Rotate

fathom prism
#

the pivot is weird

#

using the rotate tool it rotates it on the center

quick fractal
#

How would I go about playing a sound just before the destroy? Sorry if this is a very basic question

polar acorn
polar acorn
quick fractal
polar acorn
#

If it were a child objecti t'd be destroyed along with it and the sound would stop

quick fractal
#

It won't be Destroy(gameObject); for much longer

#

I'm tryign to implement health but it's confusing me a bit

#

Health & damage

fathom prism
#

but when I use the rotate tool the center is the center of all the parts

slender nymph
polar acorn
fathom prism
#

I don't know the center of all parts

#

it's very confusing because when I click on one of the parts it shows up as 0 0 0 position

#

but the whole object is far away from that

#

how do I put the pivot somewhere else

polar acorn
#

An object at 0,0,0 just means it's at the same position as its parent

fathom prism
#

it's rotating where that gray circle is

#

but I want it to rotate on this thing

polar acorn
#

What object do you have selected? Is your inspector in pivot or center mode

fathom prism
#

how do I switch the modes

polar acorn
fathom prism
#

ohhh I see

#

it was rotating around the pivot

#

and not the center

queen adder
#

How should i start learning to make 2d games. I have literally no experience in coding. I once made a game in greenfoot :/

polar acorn
#

Pivot would be transform.Rotate

shell ice
#

hi

#

im still stuck on this and i couldnt solve it

#

how can i know what unity is doiing while i am in this state , i litteraly can't debug anything because i have no clue what is going on

polar acorn
#

If this happens when you hit play, then you have an infinite loop somewhere

shell ice
polar acorn
slender nymph
#

or OnEnable

acoustic owl
#

hello

shell ice
#

i removed everywhere where code can execute

#

still happens

slender nymph
eternal needle
#

Instead of blindly guessing, attach the debugger and see what's actually happening

#

If you really have no code running, then this is a bug

polar acorn
acoustic owl
#

i'am strugling to install unity

shell ice
slender nymph
polar acorn
polar acorn
shell ice
polar acorn
shell ice
#

but those scripts are useless because i dont let them execute anything

polar acorn
#

Maybe show !code

eternal falconBOT
slender nymph
shell ice
slender nymph
#

after you attach the debugger click the break all button

quick fractal
#

I got it working, thanks guys!

slender nymph
quick fractal
#

Oh i did that cause i was using a different method

#

Thanks lol

rocky canyon
#

u can also just remove the start and update(){} to make it a bit cleaner.. if ur not using them

quick fractal
prime maple
#

Hey I got a quick question with unity. I imported a sprite and sliced them to my liking but when i put it into the scene in the game view it does not show up does anyone know how i can fix this pls

rich adder
#

also not a code question

prime maple
#

its infront of the camera and where can i ask this question?

rich adder
#

yea make sure the z position is bigger than the one on the camera

quick fractal
#

I have a kind of weird question, how would i influence an image in a canvas for something like a healthbar

#

I know i'd need to use void update(); to constantly refresh it but actually changing it is really confusing me

rich adder
#

why would you use update to refresh it?

quick fractal
#

So it's constantly checking for whether the players health has changed

rich adder
#

nahh , only change it when health goes down

#

no reason to be checking every frame that

quick fractal
#

Okay that helps

rich adder
#

yes, in time you do it via events etc..

fathom prism
#
transform.RotateAround(centerp.position, Vector3.forward, -45);

@polar acorn How do I make it not be instantly but rotate it at a certain speed

#

like make the rotate take 1/2 of a second

tacit grove
#

Hey I have a question, how do I convert mesh to a terrain and if possible convert 16 meshes into one terrain, or maybe if that's not possible convert it into terrain data and then attach the terrain component?

polar acorn
#

over multiple frames

quick fractal
# rich adder yes, in time you do it via events etc..

I know sort of how to reference scripts on the same gameobject so i could have a "Health Bar" script on the image gameobject, the "Player" script on the.. well, player and then use the player to change the "Health Bar" script which would change the actual health bar

#

Does that sound.. Right?

rich adder
#

call method to update the bar only when your health changes

quick fractal
#

gameObject.GetComponent<Health Bar>().UpdateHealth();

rich adder
#

then drag n drop the object with HealthBar script inside the inspector field

half star
#

boys and girls, we will start a study group where we will all share our goal at the start of the day and at the end of the day we will share what did we do that day. So if you are interested message me . Let's learn to codeeee! :yay:

quick fractal
#

@rich adder If i want to update the Health Bar each time i take damage, how would i go about making HealthBar.UpdateHealth; actually mean something within the script? I'm assuming i need some int reference in the health bar script

rich adder
#

you would need to create the UpdateHealth method to take in whatever data type PlayerHealth is

quick fractal
#

How would i go about making UpdateHealth a method?

#

Or rather, do you have any good docs on making methods in general

rich adder
quick fractal
#

Thanks

tacit grove
rocky canyon
quick fractal
#

Thanks, i'm incredibly new to this and probably annoying the hell out of people lmao. Should've watched a few hundred more tutorials

rocky canyon
#

if u watch the first 3 or so episodes of the series i posted you'll have plenty of context to work with..

#

knowing terminology and what stuffs called helps tremendously when first starting

quick fractal
rocky canyon
#

like if i said.. you should pass in the health variable as a parameter to the function.. someone without a clue would be like "tf did u just call me?"

quick fractal
#

My mother was a saint

rocky canyon
#

but the 3 before it get u started with terminology of scripting.. and how variables and functions work together

quick fractal
#

though I'm a year into unity and i still forget the names of tabs

#

So maybe not

rocky canyon
#

lol.. well he starts u off learning what code looks like.

#

and then teaches about the editor.. and then goes str8 into coding a game

#

this is the best tutorial, I dont feel lost even though I have no idea about coding..

#

this first comment kinda sums up how i felt too..

rocky canyon
#

and even less about everything code related

quick fractal
#

The exact thing i'm doing angry_laugh_cry

rocky canyon
#

mmhmm

quick fractal
# rocky canyon mmhmm

Just a quick thing i haven't really looked into, is playerIsAlive = false; how i change the bool?

#

Also i know i'm getting annoying so probably last thing, if i want to play a particle system on the same gameobject how would i go about doing it?
just

gameObject.GetComponent<ParticleSystem>() ParticleSystem.Play();```
rich adder
#

also IMO its bad habit to write if statement without {}

quick fractal
#

I just noticed i didn't have that lol, rectified.

rich adder
#

it works but only for the line directly underneath it

quick fractal
rich adder
#

do you know what = does ?

quick fractal
#

is equal to?

rich adder
#

no

quick fractal
#

Oh is it double ==?

rich adder
#

== is comparison yes

#

= assigns a value

quick fractal
#

So if i wanted to asign it to be false i would use one =?

rich adder
#

you want assignment, I'd say so

rocky canyon
#

you may want to look at this closer..

#

if u want to destroy the gameobject if the conditional is true. u need to wrap them all in { }s

quick fractal
rocky canyon
#

there ya go lol

quick fractal
#

So that would set the bool to false and destroy itself

rocky canyon
#

in the code above that.. it would only set the bool to false..
and the destroy(gameobject) would run regardless.. b/c it wasn't in the brackets..

rich adder
#

in Unity thats when you attach to a gameobject

#

or hit Reset on the script

quick fractal
rocky canyon
#
if(bool == true){
CallMethod();
}
CallAnotherMethod();
``` is the same as
```cs
if(bool == true)
CallMethod();
CallAnotherMethod();
rich adder
# quick fractal

well you probably had no value before when you added it in the script
no value = default is assigned which in a bool case is false

rocky canyon
#

you can omit the {}s.. but its only going to include the next line after it

#

anything else.. is considered outside the {}s

rich adder
#

that last if statement is redundant..

rocky canyon
#

no reason that i can think of to check that boolean at the bottom like that

#

b/c if it isn't giving the player damage.. it isn't gonna change the health.. and therefor.. he can't die

#

so only checking inside the ifenemy conditional would be good enuff

#

fun fact atm, the bool doesn't even matter.. b/c ur going to destroy the gameobject right after u set it to false..

quick fractal
#

If i did something like this where it's constantly checking if the bool is false and when it is, the player dies instead of having it in one if, would that be better or worse?

#

wait..

#

I removed the last if

cosmic dagger
quick fractal
cosmic dagger
#

Wait, you already have that check. Why are you doing it twice?

quick fractal
#

Ignore the bottom one i forgot to delete it lol

cosmic dagger
quick fractal
#

I'm seeing more and more how completely redundant doing this is..

rich adder
#

made it worse

#

btw code runs from top to bottom

quick fractal
#

I think this is just better

rich adder
#

also if you're destroying the object what is even the point of keeping the bool there

quick fractal
#

I'm going to replace it with a particle effect and disabling a few scripts then a respawn

#

Speaking of which, how do i disable specific scripts and play particles?

#

And respawn

rich adder
#

google "how to disable script in unity"

rocky canyon
#
    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Enemy"))
        {
            if (isAlive)
            {
                TakeDamage(damageAmount);
            }
        }
    }

    private void TakeDamage(int amount)
    {
        currentHealth -= amount;
        UpdateUI();

        if (currentHealth <= 0)
        {
            isAlive = false;
            Debug.Log("Player has died!");
        }
    }```
#

heres a snippet from one of my basic controller scripts

#

if alive -> take damage
if damage is taken -> update ui

quick fractal
quick fractal
#

With actual functions in it

rocky canyon
#

ya, or in this one

#
    private void UpdateUI()
    {
        healthText.text = "Health: " + currentHealth.ToString();
    }```
#

just updating a Text object

quick fractal
#

How do you get the text to actually show up

#

Textmeshpro?

rocky canyon
#

you create a TMPro element.. and then get a reference

quick fractal
#

And a reference is one of these? or is it a getcomponent and then modifying

rocky canyon
#
public TMP_Text healthText; ``` or
```cs
[SerializedField] private TMP_Text healthText; ```
rocky canyon
#

they're both references... they're just assigned differently

quick fractal
#

the serialized field is better for me

rocky canyon
#

you can assign a reference via the inspector. by using a public or a serialized field and drag it in yourself.
or you can assign it w/ code in a awake() or start() method

rich adder
rocky canyon
quick fractal
rocky canyon
#

yea.. typo

#

variables galore!

#

lol

quick fractal
#

and you're using.. All of them?

#

That mustve taken ages

rocky canyon
#

about 6 months.. but it is a character controller

rich adder
#

lol

#

ya need some structs my guy

rocky canyon
quick fractal
summer stump
#

playersActualSpeed is unused

rocky canyon
#

i know.. it was for a speedometer i made for debugging

rich adder
rocky canyon
#

Speedo!

rocky canyon
#

spent 6 months or so building it.. and then 1 month or so refactoring.. and just last month i deleted about 25% of it

#

soo.. another refactor or so.. and it'd be package worthy haha

rich adder
#

hey if it works it works lol

rocky canyon
#

structs, and the getter/setter properties.. took me a while to get a feel for

quick fractal
#

To detect a mouse input what do i do

#

I know the input is Mouse0/1

rocky canyon
quick fractal
#

Oh not the axis, like pressing buttons

quick fractal
#

although i'll have to remake moving it anyway so that's really useful

rocky canyon
#

(0) (1) and (2)

rich adder
rocky canyon
#

..Down ..Up

rich adder
#

but really these are easily googleable

quick fractal
quick fractal
rocky canyon
#

.. (0)

rich adder
rocky canyon
#

GetMouseButton(0)

rich adder
quick fractal
quick fractal
#

Thanks guys 😮‍💨
I'll stop bothering you all now, thanks so much for the help

rich adder
#

its no bother just trying to get you towards the right way to do it :p

rocky canyon
#

Fire1, 2, and 3

#

are also mouse inputs

rich adder
#

clicking these usually link to more info :p

quick fractal
#

I looked at the docs before hand and i have one more question

rocky canyon
#

shoot

quick fractal
#

Does this mean it blends the current animation into a new one, or blend the one you want to play into another

#

I am finally setting up attacks

rocky canyon
#

that one I dont know.. im guessing it blends the animation thats currently playing into the one u give the function ¯_(ツ)_/¯

#

could be wrong tho as I normally use parameters and set up transitions from clip to clip... just changing the parameters to let the animator handle the transitions

rich adder
#

wouldn't it be easier to just use blend tree?

rocky canyon
#

ya, since ur beginner and everything is new to you.. it wouldnt hurt to jump right into blend tree's

rich adder
#

much easier to do transitions with the graph than through code

quick fractal
#

Blend trees? Using the animator or is this code

rocky canyon
#

animator

quick fractal
#

Oh i sort of know how to use that

#

Most of what i did was using an SDK so i haven't messed much with base unity stuff 😔

rocky canyon
#

blendtree's look like this.. where u can modify that 1 single value.. and it'll blend between the 3 clips on the right

quick fractal
#

How did you get to that menu? Spam clicking the blend tree up here just sends me to the animator tab

shell sorrel
stuck palm
#
newPassive.outline.OutlineColor = playerOutline.OutlineColor = GlobalValues.playerColors[ID - 1];
#

why does this line not produce errors?

#

how can i equal something equal something

slender nymph
#

this assigns GlobalValues.playerColors[ID - 1] to playerOutline.OutlineColor and then newPassive.outline.OutlineColor. it's perfectly valid to have mutliple assignments chained like that assuming you are wanting to assign the same oject to all of them

cosmic dagger
stuck palm
#

interesting

#

thanks

quick fractal
#

Hey, so i set up my enemy script to take 10hp whenever an is trigger collider with the RustedSword tag touches it (exact same method on player) yet it doesn't seem to work at all and i can't see any errors anywhere, anyone know where i might've gone wrogn?

#

This is player if it helps

deft grail
#

a collider with IsTrigger selected, actually have the tag RustedSword?

quick fractal
deft grail
deft grail
quick fractal
deft grail
#

ok so you dont have a rigidbody

#

also this Collider shouldnt be IsTrigger most likely

#

for the enemy

quick fractal
#

The RB fixed it, thanks

quick fractal
#

For now they're just static capsules lol

quick fractal
# deft grail for the enemy

Have you ever messed with playing animations through script? I've been trying to get my attack anim to work but it constantly spits out an nre

deft grail
quick fractal
#

At least i'm not getting the NRE anymore

deft grail
quick fractal
#

Uh oh lol

deft grail
#

are you holding mouse the entire time before and after you collide?

eternal needle
#

Where do you assign the animator?

quick fractal
eternal needle
#

It is private and not [SerializeField] so theres no way its assigned

deft grail
#

why are you playing the animation here even and why on mouse press?

#

and you get no NRE because the if statement doesnt run

#

unless you changed the code to assign anim after sending screenshot

quick fractal