#💻┃code-beginner

1 messages · Page 206 of 1

summer stump
midnight sinew
#

Thank you guys

open kernel
#

object reference not set to an object, why?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class buttonpress : MonoBehaviour, IInteractable
{
    public Animator buttonAnimator;
    public AudioSource source;
    public AudioClip clip;
    public TMP_Text buttoncount;
    public int counter = 0;
    public void Interact()
    {
        counter += 1;
        source.PlayOneShot(clip);
        buttoncount.text = counter.ToString();
        buttonAnimator.SetTrigger("press");
    }
    // Start is called before the first frame update
    void Start()
    {
        buttoncount = GetComponent<TextMeshProUGUI>();
    }

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

    }
}
earnest atlas
#

probably u set it to prefab?

summer stump
summer stump
open kernel
#

for the button?

frigid sequoia
summer stump
open kernel
summer stump
open kernel
#

works now, deleted the start method

#

thank you 😄

summer stump
frigid sequoia
#

I just learnt yesterday thay I should try to not use GetComponent at all if possible so...

frosty hound
#

You're free to use it. Just cache the results when you can.

carmine sierra
#

Hi I have an issue:

I asume that the issue is that I need to use an else statement in this code, but not sure how to code it so that it freezes in it's position explicitly:

void OnMouseDrag()
{
if (weaponInstance)
{
poschange = mouseWorldPosition - originalPos;
if (poschange.magnitude <= maxLength)
{
GetMousePos();
weaponInstance.transform.position = mouseWorldPosition;
SetBands(mouseWorldPosition);
}
}
}

summer stump
opaque fox
#

Still running into issues here. The charging behavior works once and then the enemy wanders forever and can't look at the player again. The last if statement here (if Vector3.Distance(transform...) is never triggered ever and I don't know why.

open kernel
#

idk what is causing this but it looks cool

earnest atlas
#

_robotObject.SetActive(false);

will this disable the robot and its update calls?

frigid sequoia
# summer stump I would not agree with this at all

Well, I was told that is just way better to reference it directly from the inspector if possible since it is easier to mantain the reference through changes in the project and it is less demanding to have a direct reference instead of go checking a List to find it

swift crag
#

You should favor serialized references when they're possible.

#

This doesn't mean you should literally never use GetComponent.

carmine sierra
earnest atlas
#

This time I went out of my way with serializing

frigid sequoia
frigid sequoia
carmine sierra
mild mortar
#

@swift crag
Hey, I was looking over your replies earlier. But unfortunately i'm just being too stupid to really understand here.

Would you be able to point out to me exactly how you would change this to suit your modifications?

I just want it to smoothly decrease the health text when damaged, and also not have the issues with the health actually being something like 89.872 instead of 90 when I only deal int damage

using System;
using System.Collections;
using TMPro;
using UnityEngine;

public class HealthController : MonoBehaviour
{
    [Header("Health Parameters")]
    public float smoothDuration = 0.5f;
    [SerializeField]
    private float maxHealth = 100;
    [SerializeField]
    private float currentHealth;

    [Header("UI Parameters")]
    public TMP_Text healthText;
    public UnityEngine.UI.Image healthBar;

     [Header("Colour Properties")]
    public Color healthyColour = Color.white;
    public Color criticalColour = Color.red;

    private void Start()
    {
        currentHealth = maxHealth;
        UpdateText();
    }

    public void ReceiveDamage(float damage)
    {
        StartCoroutine(ReduceHealth(damage));
    }

    private void UpdateText()
    {
        healthText.text = currentHealth.ToString("0");
    }

    private IEnumerator ReduceHealth(float damage)
    {
        float damagePerSecond = damage / smoothDuration;
        float timeElapsed = 0;

        while (timeElapsed < smoothDuration)
        {
            currentHealth -= damagePerSecond * Time.deltaTime;
            currentHealth = Mathf.Max(0, currentHealth);
            healthBar.fillAmount = currentHealth / maxHealth / 2;
            healthBar.color = (currentHealth / maxHealth <= 0.4f) ? criticalColour : healthBar.color;
            UpdateText();

            if (currentHealth <= 0)
            {
                break;
            }

            timeElapsed += Time.deltaTime;
            yield return null;
        }
    }
}
rare basin
earnest atlas
#

Whats that?

#

Much of serialize I have there are just for debug

rare basin
#

Google

frigid sequoia
#

But like, we don't know how the rest of the code is working or the setup of the game

swift crag
summer stump
earnest atlas
#

Ah that, funny enough it that script mostly deals with movement

frigid sequoia
#

Probably once you have already pressed to hold the sling, it should stop checking anything else and enter a state where it just moves relative the mouse until you release it

earnest atlas
#

Yeah like 90% is movement and chasing logic

carmine sierra
frigid sequoia
#

Pretty sure it is checking if the mouse is pressed AND in range at the same time then

#

You should only check if in range to do the initial press

carmine sierra
#

not sure what you mean

earnest atlas
#

How to create an interface?

Just add new script and remove all text leaving only interface?

shell sorrel
#

public interface IMyInterface { ...

#

then you define only function signatures in it

earnest atlas
#

I know how they work, Im not sure how does unity implements them

shell sorrel
swift crag
#

There's nothing special about interfaces and Unity.

shell sorrel
#

public class MyThing : MonoBehaviour, IMyInterface {

swift crag
#

(there's very rarely anything "special" going on in C#-land)

shell sorrel
#

doing so will force you to define all of its methods

frigid sequoia
# carmine sierra not sure what you mean

If you don't show the entire code I don't think I can be of much more help, but pretty sure that you are indeed checking for two conditions in an if statement and fulfilling only one once you move out of the interaction range

mild mortar
# swift crag Store the **displayed health percentage** in a field. Use `Mathf.MoveTowards` to...

Sure, so here's what I've done.

using System;
using System.Collections;
using TMPro;
using UnityEngine;

public class HealthController : MonoBehaviour
{
    [Header("Health Parameters")]
    public float smoothDuration = 0.5f;
    [SerializeField]
    private float maxHealth = 100;
    [SerializeField]
    private float currentHealth;

    [Header("UI Parameters")]
    public TMP_Text healthText;
    public UnityEngine.UI.Image healthBar;

     [Header("Colour Properties")]
    public Color healthyColour = Color.white;
    public Color criticalColour = Color.red;

    private float displayedHealth;

    private void Start()
    {
        currentHealth = maxHealth;
        displayedHealth = currentHealth;
        UpdateText();
    }

    public void ReceiveDamage(float damage)
    {
        StartCoroutine(ReduceHealth(damage));
    }

    private void UpdateText()
    {
        healthText.text = Mathf.RoundToInt(displayedHealth).ToString();
    }

    private IEnumerator ReduceHealth(float damage)
    {
        float damagePerSecond = damage / smoothDuration;
        float timeElapsed = 0;

        while (timeElapsed < smoothDuration)
        {
            currentHealth -= damagePerSecond * Time.deltaTime;
            currentHealth = Mathf.Max(0, currentHealth);
            // Smoothly updates the displayed health towards actual health
            displayedHealth = Mathf.MoveTowards(displayedHealth, currentHealth / maxHealth * 100f, smoothDuration / timeElapsed); // Calculate smoothness based on remaining time
            healthBar.fillAmount = currentHealth / maxHealth / 2;
            healthBar.color = (displayedHealth / 100f <= 0.4f) ? criticalColour : healthBar.color;
            UpdateText();

            if (currentHealth <= 0)
            {
                break;
            }

            timeElapsed += Time.deltaTime;
            yield return null;
        }
    }
}
#

I have a question though as it has to still be wrong, I am spamming my trigger to deal 5 damage as a test, but if I do it rapidly. It seems to mess up the health somehow, for instance, I am currently on 13 health even though it should only be taking 5 damage?

swift crag
#

please share large blobs of code on a paste site: !code

eternal falconBOT
mild mortar
swift crag
#

Do not mess with how the player actually takes damage

#

Don't smear out the damage over time.

#

You're strictly smoothing out how you display your health

mild mortar
#

Hmm, could you point out to me where I'm going wrong here then?

I'm genuinely not sure where I've messed up

swift crag
#

You're starting a whole coroutine when you take damage

#

Just subtract the damage from your health. That's it.

frigid sequoia
#

You said you are managing health as ints, why are you declaring the health as floats then?

swift crag
#

That's all of your logic for changing your actual health value.

#

Then, in Update, you can smoothly move the displayed health percentage towards your current health percentage

#

You can throw out ReduceHealth entirely.

#

It doesn't make sense to start a coroutine for every instance of damage, all of which fight over the health text

#
void Update() {
  float currentPercentage = currentHealth / maxHealth;
  displayedPercentage = Mathf.MoveTowards(displayedPercentage, currentPercentage, Time.deltaTime * 3f);
  healthText.text = $"{displayedPercentage:P0}";
  healthBar.fillAmount = displayedPercentage;
  healthBar.color = displayedPercentage < 0.4f ? criticalColour : normalColour;
}
#

that's pretty much it

mild mortar
#

Okay got it, sorry about that and thanks also.

Genuinely braindead right now lol

Haven't taken a break in hours

swift crag
#

in short: separate your actual values from your displayed values

frigid sequoia
mild mortar
swift crag
#

For bonus points, extract this logic into a Healthbar component

#

It can keep track of its smoothed out values on its own

opaque fox
#

i'll do agent.transform.position tho and see if that helps

#

nope, still doesn't trigger the block

frigid sequoia
#

Add a Debug.Log to tell you the two positions you are checking and the distance between them, that usually helps a lot to spot this kind of issues

opaque fox
#

Not sure what to make of this. It charges directly towards the first known position of the player once the timer hits the certain point, but then it goes back to wandering

turbid robin
#

what is this? is in the ar project template

opaque fox
mild mortar
#

Regarding this, I just had one more question

public void ReceiveDamage(float damage)
    {
        currentHealth -= damage;
    }

    private void Update() 
    {
        displayedHealth = Mathf.MoveTowards(displayedHealth, currentHealth, Time.deltaTime * 5);
        healthText.text = displayedHealth.ToString("0");
        healthBar.fillAmount = displayedHealth / maxHealth / 2;
        healthBar.color = displayedHealth < 0.4f ? criticalColour : healthyColour;
    }

Is it not inefficient to be running this update every frame even though the health will only change on damage or healing?

I was wondering if there's a more optimal way to do this so that it is still smooth but not wasting any resource?

frigid sequoia
#

Do Debug.Log ( "Position: " + transform position + " // Target Position: " + firstPos + " // Distance: " + Vector3.Distance (transform.position, fistPos))

storm imp
#

what does this mean?

dense cypress
#

how can I square a vector

polar acorn
dense cypress
storm imp
polar acorn
low path
#

what do you mean square it/make it exponentially smaller?

storm imp
polar acorn
dense cypress
storm imp
polar acorn
storm imp
oak mist
#

Yo again, I’ve got a new asset for a turret I’m working on, it’s the sci-fi turrets (cannon) asset from unity asset store, and I want to have the user use the left and right controls to move the turret left and right (this is a placeholder, I am supposed to use a robot to move it later on, but I know how to make the change). I’ve done something similar with a very basic turret I made using cubes, the code for that is here: https://pastebin.com/6qezXDh5. I want to convert this code into now be able to change the x axis of the turret (its split into 2, the base and the gun). Are there any videos, or any steps where I can learn that.

verbal dome
storm imp
storm imp
polar acorn
# storm imp

Okay how are you actually handling clicking on this object

low path
# dense cypress get a vector (for move direction/speed) and if it goes above a certain threshold...

so you have value v. threshold t1, threshold t2 above t1. clamp v to t2 at the top. take diff = abs(v - t2). then damping = diff / (t2-t1). multiply damping by v. you could also square damping for a faster dropoff. math might be slightly off but the basic idea is you are applying a damping factor between 0 and 1 based on where your value is above your threshold, up to a full dropoff threshold (t2).

frigid sequoia
steady isle
#

I have figured out mainly all of the basics of c# and i want to start coding with unity 3d, but i dont know where to start with all of the new code

rich adder
#

plenty of resources to learn

low path
#

just start making a simple project and look up all the things you need to do

rich adder
#

bad way to learn..

low path
#

??? nah

#

how else would you learn?

raven hill
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MonkeyScript : MonoBehaviour
{
    private bool canThrow=true;
    [SerializeField] private GameObject MP;
    float targetPositionX;
    float distanceX;
    [SerializeField] private float WantedDistance;
    [SerializeField] private float speed;


    void Update()
    {
        targetPositionX=GameObject.FindWithTag("Player").transform.position.x;
        distanceX=Mathf.Abs(targetPositionX-transform.position.x);
        if(!(distanceX<=WantedDistance))
        {
            float step = speed * Time.deltaTime;
            transform.position = Vector2.MoveTowards(transform.position, new Vector2(targetPositionX, 0.2f), step);
            if(canThrow)
            {
                Instantiate(MP, new Vector3(0, 0, 0), Quaternion.identity);
                canThrow=false;
                DelayThrowing();
                Debug.Log("Threw an object");
            }
        }
    }

    IEnumerator DelayThrowing()
    {
        yield return new WaitForSeconds(0.5f);

        canThrow=true;
    }
}```

Does anyone know why the Debug.Log doesn't write anything?
rich adder
#

following a structured course

#

instead of running around like headless chicken

low path
#

that's one way but learning by doing is also a completely valid way

rich adder
#

you can't do anything if you don't know the basics..

#

like proper syntax

low path
#

they said they figured out hte basics of c#

mortal bridge
#

@mild mortarhey man you fixed it? I wrote 120 lines of codes myself in the moment (with 13 errors left to fix now)

rich adder
#

people say a lot of things, doesn't mean its true

low path
#

ok well... i've been doing this for a long time and looking up every item i want to do is how i learn

mild mortar
raven hill
#

It was under the code

mortal bridge
#

everyone can learn

rich adder
polar acorn
raven hill
rich adder
brazen canyon
#

Hey man, my Player object has the scale of 1,2,1
What do i have to do ?
I can't ruin the scale
It was originally a sphere
Can I make turn the sphere into a capsule ?

amber veldt
#

Hey guys, can you call a OnCollisionEnter function on an empty parent object?

swift crag
#

the Visual can be scaled however you want

rich adder
swift crag
#

the Player should have a scale of [1, 1, 1]

mortal bridge
#

"maybe" set it to change in update once its changed?

brazen canyon
polar acorn
mild mortar
swift crag
#

It's fine

mortal bridge
verbal dome
swift crag
polar acorn
swift crag
#

Compare your hierarchy to the one I showed you.

mild mortar
mortal bridge
#

hmmm so

#

you could do property? or coroutine? even delegate?

swift crag
#

those are various concepts, yes

#

i'm not sure why you're bringing any of them up

mortal bridge
#

to be able to update health only when it changes

swift crag
#

Have it call a method on something else.

low path
swift crag
#
public class Hitbox : MonoBehaviour {
  [SerializeField] Player player;

  void OnTriggerEnter() {
    player.Hurt();
  }
}
amber veldt
#

So I can't avoid the script on the children?

swift crag
#

e.g.

dense cypress
#

how can I restrict the force that a rigidbody has? (Stop player from going 2786 mph from holding w)

amber veldt
#

Or maybe serialize the child?

swift crag
timber tide
#

clamp your velocity

wintry quarry
dense cypress
amber veldt
#

If a child has a RB/Collider, I can't call it on a parent object, right?

wintry quarry
#

Either clamp it directly or don't add force or add reduced force when going too fast

#

another option is add drag forces

#

or use the Rigidbody drag feature built in

mortal bridge
#

I know this man he is total beginner

wintry quarry
#

Yes I know what he meant just clarifying a misconception to make his understanding more clear

swift crag
dense cypress
amber veldt
#

Yes I meant "rigidbody + collider"

#

Since you need both

swift crag
#

A rigidbody allows an object to be affected by physics. It uses all of the colliders that are parented to the object.

mortal bridge
swift crag
#

Trigger or collision messages involving the child collider will also go to the rigidbody's object

#

Although, I am not sure off the top of my head if a receiver on the child will "eat" the message

#

i.e.

dense cypress
swift crag
#
  • Root <- rigidbody, trigger-listener
    • Child <- collider, trigger-listener
#

I'm not sure if Root will get OnTriggerEnter messages

swift crag
swift crag
#

It's also very useful.

dense cypress
swift crag
#

You can add information that's specific to that collider (imagine a head hitbox that causes more damage)

amber veldt
#

Root <- script
Child <- collider, rigidbody

This is what I have, I want to trigger "OnCollisionEnter" on the root script

#

To centralize stuff you know

swift crag
amber veldt
#

Is this bad practice?

verbal dome
swift crag
#

well, if Rigidbody is non-kinematic, it'll fall away from the Root

amber veldt
#

oooooh that's why

swift crag
#

I just don't see why you aren't putting the rigidbody on the root

amber veldt
#

God dammit that makes so much sense

#

I'm an idiot

swift crag
#

The rigidbody defines what the object "is"

amber veldt
#

Ok and for the "rendering", I leave it on the child right?

swift crag
#

You generally want to parent the visuals to something else, yeah.

dense cypress
#

how can I allow player to walk up a hill/steps without a character controller because I have a rigidbody and last time I checked they don't work well together

amber veldt
#

Like Root > Collider/Rigidbody/Script
Child > Renderer?

swift crag
amber veldt
#

Ok

swift crag
#

But you can leave it on the parent if you don't have a strong reason to put it somewhere else

amber veldt
#

For the headshot/Torso shot... etc?

swift crag
amber veldt
#

Ok man, thank you, you're amazing

random totem
#

is there any way to make a line renderer keep rendering? when every my camera gets too far from the center of my line, it stops rendering even if some of the line should still be visible (like this)

swift crag
verbal dome
swift crag
#

god this test project is a mess

dense cypress
swift crag
#

that's why people like to use the CharacterController (:

mortal bridge
swift crag
#

You'd raycast downwards, starting from a little in front of your character, and see if the ground isn't much higher than the player

#

if so, raise yourself up onto it

storm imp
verbal dome
mortal bridge
#

characterController has built in var for that kind of movement. why not use it?

summer stump
frigid sequoia
#

If I have all my enemy prefabs searching for the player on Start, would it be better to have a general script just to store a reference to the player to reference it directly from there instead of searching it anew every time or it doesn't really matter?

summer stump
turbid robin
#

i have this button with the code:

using UnityEngine;
using UnityEngine.SceneManagement;
 
public class Button : MonoBehaviour
{
    public void NextScene()
    {
        SceneManager.LoadScene("SampleScene");
    }
}```
when i try to click on it it dosent take me anywere. any suggestion?
wintry quarry
#

Rather than "finding" it

polar acorn
slender nymph
wintry quarry
polar acorn
turbid robin
languid spire
mortal bridge
wintry quarry
frigid sequoia
mortal bridge
#

there has to be something there

wintry quarry
rich adder
wintry quarry
#

the code is definitely NOT running

turbid robin
wintry quarry
summer stump
slender nymph
turbid robin
wintry quarry
polar acorn
mortal bridge
wintry quarry
#

See how it says "No Function"

rich adder
#

No Function

#

literally

summer stump
verbal dome
#

I prefer SphereCast over Raycast when doing grounded/movement sensor checks. A ray can go through a tiny gap which is usually unwanted

turbid robin
#

but i dont see anything useful there

wintry quarry
#

you dragged the script in

#

that's not correct

rich adder
# turbid robin

u need to drag the script from the object
not from the project folder

languid spire
#

script instead of gameobject with script

turbid robin
verbal dome
# swift crag

I must've assumed/misremembered that it works like OnCollisionEnter, which gets sent to the rigidbody only. Which I don't see mentioned in the docs anywhere 🤔

rich adder
polar acorn
summer stump
# mortal bridge step offset?

It's quite clear you don't really understand, and that is fine. But raycast is not the alternative for character controller
Rigidbody or transform movement is.
CC USES raycasts to do what you're talking about

wintry quarry
#

it doesn't have to be the same object the button is on

#

but it could be

turbid robin
#

somethng like this?

low solstice
#

why is Length returning high values? (correct value + 1)

using UnityEngine;
using TMPro;

public class MenuUIHandler : MonoBehaviour
{
    private TMP_Text playerNameText;

    void Start()
    {
        // text GO within text area GO, not the placeholder
        playerNameText = GameObject.Find("PlayerNameText").GetComponent<TMP_Text>();
    }

    void Update()
    {
        if (playerNameText.text.Length > 0)
        {
            Debug.Log("\"" + playerNameText.text + "\" = " + playerNameText.text.Length);
            // always greater by 1 than it should be?
            // "" = 1
            // "t" = 2
            // "test" = 5
        }
    }
}
storm imp
rich adder
#

naming your script Button is a bad idea

wintry quarry
verbal dome
polar acorn
# storm imp my problem

What is your problem? I don't know what this question had to do with you adding in a debug log to check your raycast which you haven't done yet

polar acorn
turbid robin
rich adder
#

try to avoid the names unity already took, until you start learning namespaces

polar acorn
verbal dome
turbid robin
rich adder
#

isnt that what you want to run lol

polar acorn
mortal bridge
storm imp
frigid sequoia
polar acorn
turbid robin
swift crag
frigid sequoia
#

And not have a proper SpawnManager for the task

polar acorn
slender nymph
turbid robin
summer stump
mortal bridge
low solstice
storm imp
frigid sequoia
mortal bridge
#

I never do sarcasm when its about learning.

polar acorn
slender nymph
verbal dome
wintry quarry
turbid robin
#

on the unity engine i see the button in the scene, but on the build and the phone i dont see it. i thinl its because i need to set the scene to be the first, but how do i do that?

slender nymph
turbid robin
rich adder
#

but what about canvas scaler

wintry quarry
#

that doesn't really tell us anything about canvas scaling

slender nymph
#

that screenshot proves nothing

turbid robin
#

oh no it was because i didnt put the scene

frigid sequoia
rich adder
#

well might want to check scaler as well, make sure its set to scale with Screen

turbid robin
#

but now i have the sample scene (the ar one) set as 0, ant the menù set at 1. i need to change the order

rich adder
slender nymph
turbid robin
#

now lets test if scaling was right and if boxfriend won the bet

rich adder
#

proper anchoring and canvas scaler set to Screen is a must

turbid robin
queen adder
#

is instantiate real?

rich adder
turbid robin
queen adder
#

unity is telling me its not

mortal bridge
#

damn thef the hell is wrong with the fing animator? Everythings saved except for the changes I made in animator Im really sick of it. I set run static as layer default state now its idle again and also the animations are just fkin messed up

rich adder
#

yup its wrong
you need Scale With Screen and set a base resolution

#

Constant Pixel Size isn't good option

polar acorn
#

Instantiate is though

turbid robin
mortal bridge
#

Im really sick of unitys animator

rich adder
queen adder
polar acorn
eternal falconBOT
verbal dome
#

I wonder if Animancer uses AnimationClip.SampleAnimation under the hood

mortal bridge
#

never used an external one gotta check out

queen adder
rich adder
mortal bridge
#

yes

#

do we have to manually save the animator exceptionally itself or something?? is saving the project not fkin enough???

verbal dome
#

Have you tried creating a new animator controller?

rich adder
#

and you tried multiple unity version ?

#

I never seen this issue b4

verbal dome
#

Yeah, it should save without any extra hassle

frigid sequoia
mortal bridge
slender nymph
queen adder
#

on line 103 and 123 it says "cannot convert type 'UnityEngine.Transform' to 'UnityEngine.GameObject' "
https://hastebin.com/share/joyezafoxo.csharp

swift crag
mortal bridge
#

It feels so bad when you made a lot of progression just to see it mess it up itself

wintry quarry
rich adder
#

computer never is wrong

polar acorn
#

These are not the same class

dense cypress
swift crag
#

what's saying to "make a struct"?

dense cypress
#

it's an error

#

for the potential fixes

slender nymph
#

oh they've gone and thrown a tuple into the parameters for Raycast

swift crag
#

You've made a weird tuple

#

(1, 2, 3) is a 3-tuple

dense cypress
#

what's a tuple

swift crag
#

too many parentheses

#

it's a fixed-length array, basically

swift crag
#

I would suggest not cramming everything into one line

#

create a Ray out of the position and direction

frigid sequoia
swift crag
slender nymph
mortal bridge
#

if (Input.GetKeyDown(KeyCode.Space) playerIsOnGround)
{
playerAnimation.SetTrigger("Jump_trig");
}

shouldnt this work or am I losing my mind for real. player is just in his idle state

frigid sequoia
#

The player is not prefab, it is not spawned, it is just there

slender nymph
#

exactly

swift crag
#

okay, great, so you can just assign a reference to the player

slender nymph
#

so just give the spawners the reference

rich adder
#

this wouldnt even compile

swift crag
#

you can multi-select all of your spawners and give them all the reference at once

frigid sequoia
#

Is a thing on the scene, and I cannot give a reference to object on scene to a prefab

rich adder
#

!ide @mortal bridge

eternal falconBOT
swift crag
#

okay, then whoever creates the spawners is given a reference

mortal bridge
#

to make it a simpler code

slender nymph
rich adder
#

why are you sending omitted code then
that makes 0 sesnse

verbal dome
mortal bridge
#

if (Input.GetKeyDown(KeyCode.Space) && playerIsOnGround)
{
playerAnimation.SetTrigger("Jump_trig");
}

#

here you go

#

this is copy paste

rich adder
#

better

mortal bridge
#

doesnt change at all

rich adder
mortal bridge
#

yeah theres that. but it doesnt go into jump animation

#

when jumping its idle

frigid sequoia
rich adder
frigid sequoia
#

It isn't not yet implemented so I was not thinking about it sry

mortal bridge
rich adder
sharp wyvern
#
if (Input.GetKeyDown(KeyCode.Space) && playerIsOnGround)
    {
        Debug.Log("Jumping");
        playerAnimation.SetTrigger("Jump_trig");
    }``` confirmed this stuff is actually running yet @mortal bridge?
mortal bridge
verbal dome
dense cypress
# swift crag I would suggest **not** cramming everything into one line
Vector3 rayStart = transform.position + new Vector3(0, 0, 1);

//raycast direction
Vector3 rayDir = transform.TransformDirection(Vector3.down);

//actual raycast
if (Physics.Raycast(rayStart, rayDir, 1)) ;
{
    transform.position = transform.position + Vector3.up;
}```

(this might be too long and need to go into website but I can't really be bothered)

would this work?
mortal bridge
swift crag
mortal bridge
#

theres just no animation

swift crag
#

Also, you put a ; after the if statement, so it's not actually controlling the following block

dense cypress
swift crag
#
if (Physics.Raycast(start, dir, out var hit, 1f))
{ ... }
#

as described on the doc page

swift crag
#

the third parameter is out RaycastHit hit

#

an out parameter lets a method assign something into a variable

#

You can declare a variable as you pass it into the method.

swift crag
#
..., out RaycastHit hit, ...

this would also work

mortal bridge
#

everything you can ask for

#

sorry for the great wall of china.

#

Im just so sick of this animation stuff

rich adder
#

could've just madea thread..

mortal bridge
#

want it sorted out

rich adder
mortal bridge
#

Its actually somehow related to code

rich adder
#

how so you said the trigger ran ?

mortal bridge
#

SetTriggerSetBoolSetInteger

#

these 3 is all I have

#

for animation stuff

#

oh i missed the so there i thought you asked how it ran

#

so yeah it runs

#

no animations

rich adder
#

so then its not the code lol

mortal bridge
#

okay I move there then

#

let me break down the great wall of china

rich adder
#

make a video of the Animator during playmode with object selected, it will show whats happening with transitions

dense cypress
quartz mural
quartz mural
#

plzzzz help

rich adder
swift crag
#

stepLocation is not a valid type

#

consider RaycastHit, which is the correct type

rich adder
#

I dont understand video

swift crag
#

rather than the wrong type

wintry quarry
# quartz mural

Your object doesn't have a Text on it, it has a TMP_Text. Use the correct type in your code.

quartz mural
rich adder
wintry quarry
dense cypress
random totem
wintry quarry
quartz mural
swift crag
rich adder
#

jesus

swift crag
#
out TypeName variableName
wintry quarry
quartz mural
brazen canyon
rich adder
wintry quarry
dense cypress
quartz mural
rich adder
#

why not just create a new gameobject then if its gonna be blank

earnest atlas
#

How should I pass variables between scipts on the same object?

Make them public or get; private set?

rich adder
mortal bridge
#

no no where does it show it

rich adder
#

then you can inspect the transition

#

and see whats actually happenign

quartz mural
#

sorry im a begginer, if i dont use .test then what do i do 😅

summer stump
wintry quarry
#

Already told you the answer, and it has nothing to do with ".test" or ".text"

summer stump
#

TMP_Text

dense cypress
quartz mural
swift crag
#

read the documentation for the type you're using

rich adder
mortal bridge
#

but when I pause and play game again view is set to the scene again

#

I cant track it due to it

brazen canyon
quartz mural
rich adder
wintry quarry
#

listen to what is being said

verbal dome
rich adder
#

Text is the old type you have to change to TMP_Text

wintry quarry
#

through the .bounds property

mortal bridge
#

are those lines supposed to turn blue?

polar acorn
rich adder
wintry quarry
#

change Text to TMP_Text

polar acorn
mortal bridge
# rich adder blue?

well I actually dont know how to track it and nothing changes in the animator windows to be honest I checked everywhere

quartz mural
#

like this?

rich adder
rich adder
#

not even close

quartz mural
#

😭

mortal bridge
quartz mural
#

ohhhh

rich adder
#

pay attention to what was said earlier

quartz mural
#

i thnk i got it

verbal dome
#

C# basics courses wouldn't hurt you

mortal bridge
rich adder
quartz mural
#

yesss

#

i got it

#

thank u very much

mortal bridge
summer stump
mortal bridge
#

damn actually nevermind. I think animation is not my field

mortal bridge
#

I will make someone else take care of animation stuff

#

Im so sick of this already

verbal dome
#

Make sure to let them know that it might be bugged

rich adder
#

I just never seen it semi-transparent

verbal dome
#

Because yeah those are definitely supposed to not be transparent

polar acorn
verbal dome
#

Good question

dull arch
#

my animation has a blue rectangle is there a way to get rid of it

verbal dome
dull arch
mortal bridge
verbal dome
#

Ah, slightly blue tinted red

mortal bridge
wintry quarry
verbal dome
#

Try turning off the compression or using higher quality

mortal bridge
#

why are those not suppoesd to be transparent?

dull arch
#

how do i turn off compression

wintry quarry
dull arch
#

ok

mortal bridge
#

I just wanan relax myself by thinking that its not my fault but unitys fault

dull arch
polar acorn
# mortal bridge

So, the layers could absolutely explain why the animations aren't working properly, depending on your settings for them. I don't really do anything involved enough with the animators to ever need more than one, and I don't know what the "M" means. This might be a question for #🏃┃animation

mortal bridge
#

avatar mask

verbal dome
#

Maybe it has a mask with nothing selected

#

But yeah, more suitable for the animation channel

mortal bridge
#

can you come there?

verbal dome
#

Well I can take a look, but i'm no animation expert either

polar acorn
#

As I said I dunno animation I just know enough to know that when layers get involved everything I know is off the table

verbal dome
#

And there might be cases when a layer doesn't update at all if layers after it completely override it

#

Anyway moving to anim channel

dense cypress
#

how can I refer to forwards relative to the player

verbal dome
#

"unity get forward direction of object" would be a good search

wintry quarry
queen adder
#

hi, is there anyone to help me please ? I don't know how to open a file .unitypackage

queen adder
#

thanks a lot

tribal pendant
#

i'm trying to instance a prefab but for some reason it's invisible? 8it's in italian if you ned i can provid translation)

wintry quarry
#

But presumably it's just not in view of the camera

#

most likely a Z axis position problem

#

You also really need to watch out for that because you're using Vector3.Distance which is also going to include the z axis distance

tribal pendant
#

so just
mousePosPrima.z = 0;
mousePosDopo.z = 0;

#

in update out of the if

wintry quarry
#

mousePosOra.z = 0; after ScreenToWorldPoint is probably all you need

tribal pendant
#

ok it works thanks <3

tribal pendant
dusty silo
#

I have a List of Edges and have a function that takes a List of Vertecies. Is there a lambda I can use to convert the List<Edge> into a List<Vertex>? or do I need to make a separate function for that?

trim gulch
#

Hi! I'm trying to make a Play again button for my game. I am using SceneManager.LoadScene(SceneManager.GetActiveScene().name);
to load the scene again, and it seems to work, but on the restart things start to behave differently and it throws this error MissingReferenceException: The object of type 'InGameUIManager' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.

polar acorn
trim gulch
#

What's the default for that?

polar acorn
trim gulch
polar acorn
trim gulch
polar acorn
#

You have a DDOL object that references something in the scene

#

When the scene reloads that object no longer exists

trim gulch
#

How do I create it for the scene again?

polar acorn
#

Create what

trim gulch
#

The DDOL Object

#

Or like

#

What can I do about it?

polar acorn
#

If your DDOL references something in the scene, either that thing also needs to be DDOL or the thing referencing it should no longer be one

dense cypress
#

trying to recreate character controller step-going-up and this script makes me fall through the floor, not sure why. ``` //trying to make steps work

    //raycast start

    Vector3 playerFeet = transform.position += new Vector3 (0,-1,0);

    Vector3 rayStart = playerFeet += (transform.forward * 0.5f);

    //raycast direction
    Vector3 rayDir = transform.TransformDirection(new Vector3(0,-0.75f,0));

    //actual raycast
    if (Physics.Raycast(rayStart, rayDir, out RaycastHit stepLocation, 0.99f))
    {
        //make bottom of player teleport to point
        Vector3 stepLocation2 = stepLocation.point + new Vector3(0, 1, 0);


        transform.position = stepLocation2;
    }```
eternal needle
trim gulch
#

Apparently it's something with the "Rendering.DebugUpdater", I'll look into it

#

Thank you!

unreal imp
#

my dear freinds

#

is there any form to add a motion to a object which has been hit by a bullet raycast?

#

like motion to the direction of the ray

dense cypress
#

I'm no professional but could you have the raycast go a bit further then calculate the vector between the hit object and where the end of the raycast is? can't guarantee it will work at all but it's an idea

eternal needle
dense cypress
#

that's probably better

unreal imp
#
            {
                if (hit.collider.attachedRigidbody)
                {
                    hit.collider.attachedRigidbody.AddForce(ray.direction * 0.1f);
                }```
median ruin
#

is there a way to add a field in the inspector where you choose a component that is a script and choose a function from that script? What I mean is, can I make my field function specific?

low path
#

well UnityEvents let you do this, and inspectors are fully customizable... what are you trying to do?

median ruin
#

I want to make a lever that can interact with scripts

wintry quarry
#

then to call it:

onLevelPull.Invoke();```
median ruin
#

What about the receiving end?

wintry quarry
#

you make a function

#

and assign it in the inspector to the event

median ruin
#

oh okay

#

wow this is handy

unreal imp
wintry quarry
ivory bobcat
earnest atlas
#

Why this values arent shown in Unity fields?

wintry quarry
#

Unity only serialized fields

ivory bobcat
wintry quarry
#

you could add:

[field: SerializeField]``` to serialize the backing fields.
earnest atlas
#

So I need to make private values to be able to display them..

#

backing fields?

wintry quarry
#

yes

#

backing fields

#

auto properties have automatically generated backing fields

ivory bobcat
#

Maybe use field: SerializeField. Ah blue beat me to it.

slender nymph
#

you're already targeting the backing field with the Header attribute 🤔

earnest atlas
#

Those are just debug values so I can see them ingame

#

Issue is they are get; private set

slender nymph
earnest atlas
#

funny enough im not sure what field does 🙂

#

I dont remember even from where I got it

eternal needle
#

Gpt?

wintry quarry
earnest atlas
#

Im pretty sure compiler reccomended it

low path
#

oof

#

accepting suggested stuff is good if you're sure it's what you want...

earnest atlas
#

Im running on my last braincells. It takes a while before I even get what you mean xD

slender nymph
earnest atlas
#

My break will be going to sleep

#

I just want to finish logic behind enemy

slender nymph
#

don't force everyone to do your thinking for you just because you are too stubborn to take a break when you need to

earnest atlas
#

I mean I literally going to sleep in like half an hour

rare basin
#

programming when you are tired isn't a good idea

earnest atlas
#

Omg its alive

eternal needle
#

Its always "just want to do one thing". Tomorrow it will just be another thing
Take a break unless you are a slave at blizzard

earnest atlas
#

When I was playing factorio I had same "gonnado this and go rest"

#

that thing took 5 hours

swift crag
#

Get off the damn computer and take a break

#

You'll learn much more effectively that way.

earnest atlas
#

okey, gonna go sleep Ig

#

last thing

#

Why this no work

slender nymph
#

it is get only

earnest atlas
#

as I though

low path
#

can still set it in the inspector though i believe

slender nymph
#

incorrect. get only properties generate a readonly backing field which cannot be serialized by unity

low path
#

ahh

fierce sonnet
#

Hi, i am currently programming a evolution simulation 2d and i have problems programming the Raycast part of it

Code: https://gdl.space/zecinireyu.cs
The code runs in FixedUpdate

The problem is that even though (form what i can see with the DrawLines) they never turn green and even if they hit their target they sometimes if you wiggle them a lot maybe somtimes they see them. I have tried many youtube videos and asked also gemini but they couldn't help me
Thanks 🙏

calm dust
#

can sopmeone with codoing experience help me

#

im having trouble with my code

#

i cant find anything online to help

river roost
low path
#

whats your quwstion?

calm dust
#

me?

rare basin
fierce sonnet
rare basin
#

send the code you are having issues with

#

how can we help you without any context

calm dust
#

fair enpough

fierce sonnet
calm dust
#

it is in playerinput but its not working

spare mountain
river roost
slender nymph
# calm dust

make sure that your !IDE is configured so that it will suggest properties that actually exist while typing the code

eternal falconBOT
calm dust
#

theres more hold on

polar acorn
eternal falconBOT
spare mountain
#

why are you declaring a variable of type onfootactions?

calm dust
#

hold on

spare mountain
#

also you need to configure your ide

calm dust
#

i have more code

slender nymph
#

they've probably spelled the name wrong or not saved their input action asset

calm dust
#

yea i dont know how to do that

spare mountain
slender nymph
calm dust
#

ok

#

how do i do that?

spare mountain
#

🤦‍♂️

calm dust
#

oh wait

low path
#

i think they need to start with some c# basics tbh

spare mountain
dusty silo
#

Does On(Dis/En)able apply to the object a script is attached to, or the script itself?

slender nymph
dusty silo
# polar acorn Yes

Is there a way to specifically disable a script while leaving the object alone?

#

There isn't a check box next to scripts in the inspector

slender nymph
#

you can enable or disable a component using that components enabled property

river roost
#

set the enabled property to false

polar acorn
slender nymph
polar acorn
dusty silo
#

Okay, thanks.

calm dust
#

ok, i configured it

slender nymph
#

do you see red underlines in your code now

calm dust
#

yes

spare mountain
#

yay

spare mountain
slender nymph
calm dust
#

ok done

slender nymph
#

has the error gone away?

calm dust
#

no, another one came up

slender nymph
#

care to share? remember nobody here can see your screen

calm dust
#

sure, hold on

spare mountain
calm dust
slender nymph
swift crag
#

ah

#

that name overlap is awful

slender nymph
# calm dust

congrats, you did not follow the tutorial correctly

spare mountain
#

rip

calm dust
#

lemme double check

slender nymph
#

keep in mind that spelling matters, including capitalization

median mortar
#

Hey guys, what kind of timers do you prefer in unity?
C# Timers (System.Timers), a simple Coroutine, C# Async?
Wanna set a timer that destroys an object if it doesn't hit anything in a specific time

summer stump
#

Is this that tutorial from Dave something (Dave Makes Games?). That one has caused so much confusion for people

slender nymph
median mortar
#

Does Unity has its own Timer implementation?

median mortar
summer stump
#

Either accruing deltaTime, tracking differences in Time.time or a coroutine

slender nymph
calm dust
#

i followed it exactly

summer stump
slender nymph
calm dust
#

ok

#

hoild on

median mortar
slender nymph
#

no but you never specified that 🤷‍♂️

summer stump
#

If you want cancellable, I would cache a coroutine and stop it with StopCoroutine if needed, or accrue deltaTime and halt it if needed

spare mountain
#

invokes are cancellable

slender nymph
#

invoke is gross because it uses reflection, but yeah it would technically work

calm dust
#

its not there

#

thats really weird

#

i will restart it

median mortar
calm dust
#

@slender nymph

slender nymph
#

and the inspector when you've selected the input action asset

calm dust
#

i dont know what that means, im sorry

polar acorn
slender nymph
#

you know the thing you double clicked to open that window? click that thing once and look at the inspector window

spare mountain
slender nymph
polar acorn
calm dust
slender nymph
#

so you remember how i said spelling including capitalization matters?

#

you need to fix the class name either right there or in your code. then you need to spell the action name correctly in your code too

calm dust
#

i did that but the error is still there

summer stump
calm dust
#

in the code

summer stump
calm dust
#

Playerinpu

spare mountain
calm dust
#

typo

spare mountain
#

ok

polar acorn
#

Well if you put this much care into typing your code as you put into Discord I can see where your problems are coming from

calm dust
#

funny

spare mountain
#

what's the error say now @calm dust

summer stump
calm dust
spare mountain
#

something is afoot

summer stump
spare mountain
#

that too

summer stump
#

Change the type, not variable name

#

And readvalue is not a thing

#

Remember that capitalization matters

slender nymph
#

they just have a whole bunch of spelling mistakes

polar acorn
#

Basically, instead of having us spell check everything for you one thing at a time, configure your !ide and go retype it all properly this time

eternal falconBOT
spare mountain
#

they just don't know how to use that

#

😔

polar acorn
slender nymph
#

they claimed to have configured it. we have no proof thtat they did

calm dust
#

well, i did what the website said. the website that the bot linked

slender nymph
#

screenshot your code

spare mountain
#

took the words out of my mouth

calm dust
#

just so you know, i did what @summer stump told me toi do and changed the other onej

rich adder
spare mountain
#

let's not play the blame game

calm dust
#

no no no

#

not what m doing

spare mountain
#

show your codeeee

calm dust
#

it looks different and im just telling u why

calm dust
spare mountain
#

it is configured at least

summer stump
#

You did not do that clearly

#

Because in four places the type is still PlayerInput

spare mountain
#

😮‍💨

summer stump
#

I will give you one though. You changed ONE of the five places

spare mountain
# calm dust

make every PlayerInput -> Playerinput first of all like we said

calm dust
#

its back down to 2

spare mountain
#

second fix your variables

spare mountain
calm dust
#

sorry hold on

spare mountain
#

and you didn't even do what we said 😭

summer stump
#

Still not all the Playerinputs have been changed

slender nymph
summer stump
#

EVERY place it says PlayerInput needs to be Playerinput

spare mountain
calm dust
#

ok

spare mountain
#

it has no name

polar acorn
# calm dust

Don't make a variable the same name as the type

calm dust
#

ok

summer stump
slender nymph
# spare mountain it has no name

because they put the type name there instead of their variable. they don't need a local variable there, they need to assign to their existing field of that type

summer stump
#

This damn tutorial man. This happens every time

polar acorn
#

Seems like at least twice a week we have someone who doesn't name their assets right

slender nymph
#

pretty sure it's a super short one that just shows you how to do the stuff instead of explaining how and why you are doing the things

summer stump
#

bad but appealing

calm dust
#

i dont know what i should rename my variable too

summer stump
calm dust
#

ok

polar acorn
#

Call it Kermit for all it matters

slender nymph
calm dust
#

im getting different answers

#

i dont know what to do

polar acorn
#

Which you had but then you changed because you didn't know what a type was

slender nymph
# calm dust

your code here is correct except for the spelling of the types and the spelling of the ReadValue method (which you have already fixed). You went and changed the type names and replaced the variable being used inside of Awake with the type name

calm dust
#

should i just restart?

spare mountain
#

you're so close

#

you've got like 2 minor issues

#

why restart

calm dust
#

ok

polar acorn
#

Then you'll stop using one where you need the other

swift crag
#

A variable is defined by two things:

  • The type of the variable is what it holds. int, float, MyComponent, GameObject
  • The name of the variable is what it's called. counter, damage, targetComponent, myObject

A variable is declared by writing both the type and the name of the new variable:

SomeType someName = ...

On the other hand, this is not a declaration:

someName = ...
low path
#

honestly i think they could benefit from some short-ish but fairly intensive c# practice. like go do leetcode easy or exercism.io or something.

calm dust
#

ok, i changes the variable to input, changed hoppefully the right ones to input, but now theres 2 problems

swift crag
calm dust
slender nymph
#

rather see the actual code than screenshots of the error messages

swift crag
summer stump
#

You changed the type to input. That was just for the name

polar acorn
summer stump
polar acorn
#

At this point it's clear you simply do not know enough C# to even receive answers. Hambones was right, you should learn enough C# to at least understand the explanations you're being given. Consider one of the things suggested by them or linked in the pins.
#💻┃code-beginner message

spare mountain
#

it's like flipping random switches

#

and hoping the light turns on

calm dust
#

so should i change the code to Playerinput input = new Playerinput

summer stump
#

That would make a local variable

potent nymph
swift crag
spare mountain
swift crag
#

That's why.

summer stump
swift crag
#

The Unity serializer only cares about things that are [System.Serializable]

potent nymph
#

as far as I've read, "Serializable" means I'm saving something as a file, which I'm not doing

swift crag
swift crag
#

It does not mean to write that data to a file.

#

You do frequently write that data to a file, of course

#

but serialization is also used for things like sending data over a network

potent nymph
#

but I'm not sending data over a network either
I'm actually receiving JSON

swift crag
#

You don't just directly copy a blob of memory over the network; you turn your object into data, send that data, and then have the other party unpack that data back into a C# object

potent nymph
#

shouldn't it be deserialization...?

swift crag
#

I am just giving examples of what serialization is.

#

And yes, you're deserializing data back into an object.

#

The type must have the [System.Serializable] attribute.

turbid robin
#

is there away to ask what scene to load? something like a pubblic variable?

swift crag
polar acorn
polar acorn
swift crag
#

I believe you can then specify a string in the OnClick entry

summer stump
swift crag
#

oh, do you mean you want to show a popup?

#

and get some user input?

turbid robin
#
pubblic class SceneName;

something like this?

polar acorn
#

how did you get that from what we said

turbid robin
#

i create the parameter

summer stump
#

You don't want a class

#

String or int

swift crag
#

that's a small blob of invalid syntax

swift crag
turbid robin
#
using UnityEngine;
using UnityEngine.SceneManagement;
 
public class Button : MonoBehaviour
public str SceneName;
{
    public void LoadScene()
    {
        SceneManager.LoadScene(SceneName);
    }
}```
like this?
swift crag
#
public void DoThing(string something) { ... }
rich adder
#

lol

rich adder
#

guesswork

polar acorn
rich adder
#

c# courses pinned

polar acorn
#

Don't just guess at syntax

#

Please

#

If you don't know what a word is, look it up

turbid robin
#

my luck was not at my side

polar acorn
#

dont just throw code in random places

turbid robin
#

i remember i did it once, i just dont remember what i did ahha

polar acorn
turbid robin
#

oh yeah now i remember

#
using UnityEngine;
using UnityEngine.SceneManagement;

public class Button : MonoBehaviour
{
    public string SceneName;
    public void LoadScene()
    {
        SceneManager.LoadScene(SceneName);
    }
}```
like this?
summer stump
#

No

swift crag
#

this is completely bogus syntax

#

you can't just randomly smash lines of code together

turbid robin
#

no? this this time i didnt try to guess

summer stump
#

Sorta closer, but misunderstanding the absolute most basics of programming

rich adder
#

lol

polar acorn
slender nymph
summer stump
swift crag
#

Hey, that's a lot closer

turbid robin
#

inside the class now

summer stump
#

Now, what are parameters? And where do they go?

turbid robin
#

it works

#

i put the prameters on the unity project

swift crag
#

This will work if you always want to go to the same scene.

#

you did not put the "parameters" on the "unity project"