#💻┃code-beginner

1 messages · Page 630 of 1

hidden fossil
#

anyone here know how to like code a heatlhbar?

#

!code

eternal falconBOT
hidden fossil
slender nymph
#

sprinkle some logs in there to make sure the methods are being called as you expect them to be

hidden fossil
#

hmm ok

#

how do i collapse that console it keeps spamming random messages that i dont want?

#

does anyone know how?

slender nymph
#

okay so have you confirmed that the methods are being called as you expect?

hidden fossil
#

yep

#

but the healthbar isnt updating

#

thats the main problem

slender nymph
#

show the code with the logs so i can see what you actually logged. and also show the logs in the console

hidden fossil
#

!code

eternal falconBOT
slender nymph
#

you know you can bookmark those links in your browser so you don't need to use that command every single time you want to share code

hidden fossil
#

console

slender nymph
#

okay so it does appear to be modifying the fillAmount correctly. are you sure nothing else is affecting it? or that you are looking at the correct instance?

hidden fossil
#

nothing else is affecting it

queen adder
#

need help on this, player doesn't jump when i hit spacebar but movement right and left work fine. Thanks

rich adder
hidden fossil
#

can someone tell me why my healthbar isnt updating?

#

console

rich adder
#

i dont see it logged anywhere in console

slender nymph
#

it's in there

hidden fossil
#

19:39:04

rich adder
#

oh wops im blind

slender nymph
hidden fossil
#

i have no animation in my game

#

well i have one but it doesnt work

rich adder
#

whats it look like in the scene

#

can you show

hidden fossil
rich adder
#

yea like the healthbars

hidden fossil
#

video or pic?

rich adder
#

pic should be fine, show the inspectors + components

slender nymph
hidden fossil
slender nymph
queen adder
# queen adder need help on this, player doesn't jump when i hit spacebar but movement right an...
{
    private float horizontal;
    private float speed = 8f;
    private float jumpingPower = 16f;
    private bool isFacingRight = true;

    [SerializeField] private Rigidbody2D rb;
    [SerializeField] private Transform groundCheck;
    [SerializeField] private LayerMask groundLayer;

    void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal");

        if (Input.GetButtonDown("Jump") && IsGrounded())
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
        }

        if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
        {
            rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
        }

        Flip();
    }

    private void FixedUpdate()
    {
        rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
    }

    private bool IsGrounded()
    {
        return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
    }

    private void Flip()
    {
        if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
        {
            isFacingRight = !isFacingRight;
            Vector3 localScale = transform.localScale;
            localScale.x *= -1f;
            transform.localScale = localScale;
        }
    }
} 
hidden fossil
eternal falconBOT
slender nymph
rich adder
hidden fossil
slender nymph
#

this is not a filled image

rich adder
#

no wonder it wasnt working 😛

hidden fossil
rich adder
#

change Image type

#

to Filled

hidden fossil
#

oh

#

thanks guys im an absolute dum***

rich adder
#

it happens

hidden fossil
#

how would i fix this glitch where instead of going from down to up it would go side to side?

#

oh wait nvm i found the method

pine crater
#

Hi I have a unity project for my coursework which is a toothbrushing game. I have it so that a polishing type sprite appears when a tooth is clicked on, and then it disappears a second later. I have done this by using the OnMouseDown function for enabling the sprite and then a seperate function called Hide for disabling which is called from within OnMouseDown. All works well but I have a problem. If there are too many successive clicks, the sprite only appears for a fraction of a second, as if the coroutine isn't working properly, almost like jump fatigue 😂, does anyone have a fix for this?

#

Here are my functions

private void OnMouseDown() {
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePosition.z = 5f;
sprite.transform.position = mousePosition;
sprite.enabled = true;
StartCoroutine(Hide()); }

private IEnumerator Hide() {
yield return new WaitForSeconds(1);
sprite.enabled = false; }
eternal needle
pine crater
#

How do I do that

#

I'm not used to coroutines if I'm being honest

eternal needle
#

Pretty much exactly how I described. Use the return value from the start coroutine method and store that in a coroutine variable.

pine crater
#

So I declare my data type as Coroutine?

eternal needle
#

Yea the stop coroutine method takes a coroutine in as the param

pine crater
#

I understand so I do private Coroutine answer = StartCoroutine(Hide());
But where do I call the StopCoroutine function?

#

In the OnMouseDown function?

slender nymph
#

you can't start the coroutine in the field initializer, you would just assign to that answer field where you normally start the coroutine

eternal needle
# pine crater I understand so I do private Coroutine answer = StartCoroutine(Hide()); But wher...

Look at one example in the docs above, you dont call start coroutine outside of a method.
but yes you would call stop coroutine in OnMouseDown, check if the coroutine is null and if it isnt, call stopcoroutine on it. At the end of hide() you can set the coroutine to null.
So coroutine starts, answer gets the return value from start coroutine, then answer is set to null when the coroutine finishes

pine crater
#

Literally the word null?

eternal needle
#

Yep it's a keyword, you can set the coroutine to null. In this case itd mean there is no currently running coroutine

pine crater
#

Okay perfect thanks for your help brother

#

It's 4am rn sorry for my drowsiness

snow ravine
#

Hey i have a hopefully simple question/problem. Ive made a very simple game for android - it built and installed etc fine, however whenever i try to tap on the objects to break them, the event doesnt work. I'm using OnMouseDown() since I was under the assumption that would handle Tap input on gameobjects however it doesnt seem to work.
(Im new to unity, moving from UE5)
How do i make it so it registers me tapping on a gameobject with a collider2d on it ?

gentle bone
snow ravine
#

yeah im using the new input system. I'll give that a go

snow ravine
#

didnt work. thanks though.

wintry quarry
#

You need to make sure there's an event system in the scene and a Physics Raycaster on the camera.

The code needs to be correct as well

snow ravine
#

I didn’t even think of the physics raycaster xD unity is more complicated than unreal. Unreal it’s just a node in blueprints plug and play haha

wintry quarry
snow ravine
#

No I get it. I was using UE for almost 10 years and completely forget out much I struggled learning that so it’s frustrating learning something in a new workflow when you can do it easy in another Yknow? Same from 3ds max to blender :p

ruby merlin
#

Do anyone know how to get current sprite of rule tile in code. I can't find it in web. In the script i have that variables:

public Tilemap tilemap;
public Sprite targetSprite;
silent rapids
#

Anyone knows how to fix this? I am new to unity and coding, I made a project and I am following a tutorial, it said create a c# code in a folder, but when I look the only thing of code that pops up is monobehaviour and no C#, anyone knows the reason / how to fix it?

keen dew
#

You can use that. The only difference is the default contents of the file

#

and don't cross-post

fringe valley
#

Anyone got tips or resources on why sprites may jitter and be super buggy in unity2d when moving fast, even when enabling interpolation to the rb and using fixedupdate

silent rapids
keen dew
#

Posting the same message to multiple channels

snow ravine
#

@wintry quarry @gentle bone thanks so much for you help guys! got it working finally. ive spent the last 2 days googling and everything XD

thin birch
#

Hi, I don't understand why my normal map behaves this way

#

it's transparent technically

#

it adds this weird background

eternal needle
thin birch
#

ah I see

ruby zephyr
#

yoo guyss, as I finished unity essentials pathway and started the Junior Programmer halfway, I can say that I am finally Learningg!!!🤩

I literally came from a tutorial trap to believing that Flappy bird is actually so easy to make now... Unity learn really does the job.

stray wigeon
#

Do I understand correctly that unlike UE5, Unity Overlap spheres/boxes are only at code level and are not visible on the level? Is there maybe any add-on that adds this functionality to Unity?

runic lance
#

otherwise it's always possible to use Debug.Draw ou gizmos

tiny rain
#

Hi guys, C# question here-

When exactly does array indexing pass an element by value, and when exactly is it a reference?

#

I know that there're tricks that allow you to seemingly bypass the pass by value issue that struct in arrays has

#

For example, writing a function where you pass a value in with the ref keyword, that one allows you to modify array elements directly within the function

sour fulcrum
#

Your question isn't tied to arrays afaik

#

value types aren't passed by reference unless they are explicitly used with the ref keyword

#

otherwise they are just values

tiny rain
#

Well, why I'm asking about arrays specifically is since setting a value in a struct in a struct for example isn't a problem...

sour fulcrum
#

structs can hold reference types, but the struct itself is a value

tiny rain
#

I'm having kind of an abstraction issue where I don't want to permit direct access to the map, so I added a function to get a chunk- But then the problem is that I have no idea how to pass a chunk out as a reference

#

Like, the cleaner looking the better

#

There're some ways but I'd really prefer not to use those

#

Ah, nvm, I think I found what I was looking for- Seems like I was never aware that return value may also use the ref keyword

#

My bad '^^

#

Been searching a while but the fact to search "c# return struct by reference" never actually cross my mind

thorn holly
scarlet aspen
#

Imagine doing a simple unity learn essentials beginner course and seeing this

ember tangle
#

So I have implemented this as it seems like the best choice for what I am doing, but I cannot access the struct list the spawn tables inherit in the inspector. Here is what it looks like now compared to before:

#

Here is the scriptable object with the list that is being inherited ```public struct SpawnChance<T>
{
public T type;
public int chance;
}

public class SpawnTable<T> : ScriptableObject
{
public List<SpawnChance<T>> spawnChances;
}```

and here is the scriptable object in questions [CreateAssetMenu(fileName = "RoomSpawnTable", menuName = "Scriptable Objects/RoomSpawnTable")] public class RoomSpawnTable : SpawnTable<RoomType> { }

cloud walrus
#

What i exactly want to do is to make the collision smoother and to disallow the player from moving through the spinner

rocky canyon
#

interpolation makes it smoother..

#

detection changes its precision

cloud walrus
#

thx!! I appreciate your help i'll try it now

bright zodiac
#

I'd just pass their indexes if I were you, refs and outs will add extra indirection... not a big deal ofcourse

tiny rain
#

But when you stored it, it won't be a reference anymore pretty sure?

bright zodiac
#

if that's what you want just pass their indexes

#

dont use ref or out at all

tiny rain
#

Ye... Except it would show the (kind of unintuitive) innerworking...

bright zodiac
#

wdym?

tiny rain
#

Since the map are chunks but then splitted into tiles

#

So if you wanna access a tile, you would actually have to access a chunk at index position divided by chunk size, and then access the tile inside it

bright zodiac
tiny rain
bright zodiac
#

I mean, why not? we're not Picasso, we don't make things look pretty

tiny rain
#

Consistency and readability is typically highly recommended, though...

bright zodiac
#

do you think accessing them via indexer to be unreadable?

#

again it's a matter of preference

tiny rain
#

Maybe

#

It's just pretty inconsistent with how to access tiles

#

Though honestly what makes sense depends on how you think about things

cloud walrus
rocky canyon
#

if u use translations physics aren't respected

bright zodiac
rocky canyon
#

so if any of ur code is transform. = blabla <-- thats teleporting the object directly..

tiny rain
cloud walrus
bright zodiac
#

shit i forgot this is code beginner

tiny rain
#

I mean, it's either pass back by reference, or indexing...

bright zodiac
#

just use indexers and call it a day imo

tiny rain
#

Hmmm... Hey, could I have your opinion on something

surreal kernel
#

anyone has an idea why in my gameover screen there is no mouse to see, so you cant click on anything

#

i have many small problems with my game hahga

#

but idk how to fix them

tiny rain
#

Are you perhaps in FPS mode?

#

Basically did you use lock cursor?

surreal kernel
#

iam but iam changing scene

#

could be iam using the default fps controller

tiny rain
#

Depends on how you expect it to work...

surreal kernel
#

in the main menu its working

cloud walrus
# rocky canyon goes for the tank too..

this is the code of the spinner:


public class Spinner : MonoBehaviour
{   [SerializeField] float xAngle = 0f;
    [SerializeField] float yAngle = 0f;
    [SerializeField] float zAngle = 0f;
    Rigidbody myRigidbody;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        myRigidbody = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        Quaternion currentRotation = myRigidbody.rotation;
        Quaternion deltaRotation = Quaternion.Euler(
            xAngle * Time.fixedDeltaTime,
            yAngle * Time.fixedDeltaTime,
            zAngle * Time.fixedDeltaTime
            );
        Quaternion newRotation = currentRotation * deltaRotation;
        myRigidbody.MoveRotation(newRotation);
    }
}

And this is the code i'm using for the tank:

using UnityEngine.InputSystem.Interactions;

public class Mover : MonoBehaviour
{
    [SerializeField] float moveSpeed = 7f;

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

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

    void PrintInstruction()
    {
        Debug.Log("Welcome To The Game!");
        Debug.Log("Move using key arrows");
    }
    void MovePlayer()
    {
        float xValue = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
        float yValue = 0f;
        float zValue = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
        transform.Translate(xValue, yValue, zValue);
    }
}
tiny rain
rocky canyon
surreal kernel
#

right when oyu die it is switching scenes

rocky canyon
#

but ur player move script is using translation

cloud walrus
#

OHHHH

rocky canyon
#

transform.Translate.. <-- that wont respect physics

cloud walrus
#

that's what's causing the error

rocky canyon
#

heres a good video that explains the different types of movement

cloud walrus
#

Thanks man!!! I really appreciate that

tiny rain
cloud walrus
#

Now i know what to fix!

surreal kernel
#

ty

tiny rain
#

I'm quite certain it's simply that the cursor's lock state doesn't reset upon switching scenes

surreal kernel
#

probebly

rocky canyon
#

a singleton.. <-- its wat keeps track of cursor

#

and if anything wants to lock or unlock it it needs to go thru that script

tiny rain
#

Yea but... I don't think they wanna go through the hassle of making a whole system lol

rocky canyon
#

(1) place modifying it.. soo only (1) place things could go wrong..

#

true.. its the premise more than anything..

tiny rain
#

I made my own cursor manager too, and stacking input manager and what not, so yea... It's not that I don't know how to do things properly, it's just that it feels wrong to suggest such a route for a beginner

rocky canyon
#

i just had a long conversation the other day.. where this guy was manipulating the cursor state.. in his player controller..

#

in his pause menu.. and a few other places..

#

just asking for a bad time

tiny rain
rocky canyon
#

just a Manager type script.. that his other code could call..

#

instead of handling the cursor lock state on its own..

#

and since its a singleton.. it carries over to all scenes..

#

ezpz 🍋 squeezy

#

TLDR: control ur cursor from (1) singular place..

hexed nymph
#

Yooo is there a way to set the "raycastTarget" with a script? if so how can I do that?

rocky canyon
#

referenceToSaidScript.raycastTarget = theThingYouWantSet;

hexed nymph
#

I want to call it in the "ChangeScene" script

surreal kernel
#

using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;

public class SceneChanger : MonoBehaviour
{
public void LoadScene3()
{
SceneManager.LoadScene(3);
StartCoroutine(UnlockCursorAfterDelay());
}

private IEnumerator UnlockCursorAfterDelay()
{
    yield return new WaitForSeconds(0.1f); 
    Cursor.lockState = CursorLockMode.None;
    Cursor.visible = true;
}

}

#

With these script i still have no courser

#

maybe its an other problem?

eternal falconBOT
dry folio
rich adder
tiny rain
tiny rain
#

I'm pretty sure that Coroutines are stopped when the Object has been destroyed

hexed nymph
#

does anyone know how to do it?? 😭

rocky canyon
#

the link i sent describes all the ways to get references to other scripts..
the easiest which is [SerializeField] MyScript referenceOfScript;

#

then u can just assign it in the inspector.. (also have to make sure any variable or method you're wanting to access outside that class is public)

hexed nymph
#

I did this

surreal kernel
#

it dosent print anything

rich adder
slender nymph
rocky canyon
# hexed nymph

u could use an Image variable and not need to use the extra GetComponent if u wanted to

rocky canyon
ember tangle
rocky canyon
#

ofc it did lol

hexed nymph
#

I tried to do that before but it didn't work

rocky canyon
#

might have needed the using statement at the to

#

to interact w/ unity's UI

hexed nymph
#

thanks anyways

rocky canyon
hexed nymph
rocky canyon
#

eh.. no idea then

#

good its working now tho

hexed nymph
#

yeah

rocky canyon
#

same concept can be applied to pretty much every type

#

if ur only using the gameobject to grab some other component.. u can use it instead..

#

and its easier to work backwards.

#

can get the gameobject off of the component instead

ember tangle
surreal kernel
#

can someone help me why ma animation isent playing on my mosnter charakter?

#

idk how to mark it as "legacy"

slender nymph
queen adder
#

how do i get this movement to work

#

the x and y are the errors

ember tangle
runic ledge
#

!code

eternal falconBOT
bright osprey
queen adder
young jetty
#

anyone know a good resource for developing photon fusion hostclient firstperson character controller?

queen adder
#

this is where i have defined everything

bright osprey
#

ignore my last message - i assumed angular velocity was always a vector. Im going to look at some docs 🙂

#

so your angular velocity.x and angularVelocity.y wont exist at all and the vector assign wont make any sense. You have to assign a float not a vector

calm adder
#

Can someone help with my code? Its not working and im not sure why. Its mainly the sprinting feature. Also am i supposed to paste the whole script? (Its 154 lines long) or do i just take screen shots of the main part?

calm adder
# calm adder

theres more code its just that its not related to the sprinting part

bright osprey
#

!code

eternal falconBOT
naive pawn
bright osprey
#

new at unity - not so new at c# 🙂

calm adder
naive pawn
#

see the ! code embed above

calm adder
bright osprey
naive pawn
calm adder
keen dew
#

staminaIsRecharging starts as true so the loop in the coroutine is immediately skipped

calm adder
#

is that the only issue?

keen dew
#

That's the immediate reason why no other logs show up, I can't run the entire code in my head

gray orbit
#

ello what is up

#

I think I am missing something fundamental here but can anyone shed some light here:

I have created a test folder in unity that lives at Assets/Scripts/Tests and have a bunch of public classes I want to access defined in Assets/Scripts. I'm having trouble getting my test script to reference those classes as they are not defined in the context while I'm running my script. Can someone help explain to me what is going on with the scope and context here when I run tests through Unity TestRunner?

bright osprey
#

you may need to add your assembly definitions *

slender nymph
#

Yeah for the test runner you should be using asmdefs for your own code that your test asmdef references

noble forum
#

public object[][] weapons = new object[5][];

weapons[0] = new object[] { "Blaster", blasterimage, "A gun shooting homing projectiles", blasterchosen, "bla", (Action)blaster};

how can i add the void method to onclick in my button?karta1.onClick.AddListener((UnityEngine.Events.UnityAction)weapons[x][5]);
ive tried this but it doesnt work any ideas pls

amber spruce
#

hey so i need some help making a upgrade system for my game so basically im making a mobile game similar to games like idle miner and adventure capatalist and i have stands that every time i click them they take X amount of time and generate X amount of cash but i want to be able to upgrade it so you can make it quicker and generate more cash each time but im not sure of a good way to do this without it getting out of control way to fast

i also plan on adding more areas that let you get more money faster each area will have 6 stands

my current stand script is this https://pastebin.com/evEkkC1T

and currently if you upgrade 1 stand to have like 20 price upgrades 5 cook time upgrades and give it a chef you can get to trillions super fast which i dont want it to be able to do (with max upgrades for the area for all 6 stands and a chef you should be barely getting a million (i havent added a max for the upgrades yet but i would like it to be like a max of 50 for price or smth and like 10 at least for cook time))

noble forum
#

in the object it was just action so i had to change it to UnityEngine.Events.UnityAction and it works perfectly

naive pawn
#

try to avoid excessive casts

noble forum
cosmic quail
naive pawn
#

try googling "c# struct"

noble forum
# naive pawn try googling "c# struct"

i dont think it would fit my idea here. i saw i could use classes instead of objects but ive watched videos explaining them and i still understand nothing so i just went with objects will it be really bad?

sacred lake
bright osprey
#

object is the base class for all classes in .NET (c#). While it means you can store anything in the array - it means accessing it gives you anything. It makes maintainability very difficult alongside boxing/unboxing issues all over the place

naive pawn
#

they just aren't object

#

object is very broad, it's like saying "an array of something"

#

using a struct/class gives you names for the members as well

bright osprey
bright osprey
naive pawn
#

oh damn it does, nvm sorry

bright osprey
#

i believe its as i said above - gooing from value type to reference types

naive pawn
#

yeah

sacred lake
naive pawn
#

i didn't realize it would do that implicitly with object
i was thinking of how that works in java, where there's corresponding value and reference types that can box/unbox

amber spruce
naive pawn
amber spruce
# naive pawn you don't have any punctuation, what's your actual question lol

yeah sorry about that. my question is mainly how i can improve what i have so instead of after only a few upgrades being able to make trillions of cash. i want to be able to have all 6 stands be maxed out with like 50 upgrades for price and like at least 10 for time and still barely be able to get a million

#

idk if the issue is my math or smth

mighty cosmos
#

any tutorials you guys recommend about clean code?

naive pawn
#

maybe linear, maybe exponential, maybe polynomial
open up desmos and try finding a line/curve that has values that scale well with your economy

amber spruce
# naive pawn scale the upgrade cost

issue with that is there is no real way to scale the upgrade cost to fix this because it goes from making nothing to making trillions way to fast

#

so if i scaled the upgrade cost people would need to spend hours before they could get there first upgrade

naive pawn
#

er no?

#

the first upgrade would probably be the same value

bright osprey
#

you can also apply a curve to things like upgrade cost as suggested above

naive pawn
#

i don't mean "make all your upgrades twice as expensive"
i mean "make subsequent upgrades more expensive"

#

like if the first upgrade costs 10, the next might cost 20, then 45, then 100, then 230, then 475, etc

amber spruce
naive pawn
#

if progress scales up, then costs should also scale up

#

if progress scales too much, either reduce progress, or increase costs

#

this isn't really a code issue

bright osprey
#

theres always an idea of a prestige after X amounts of cash 🙂

naive pawn
#

it's a design issue

rocky canyon
#

ohh. we balancing! ⚖️ ? im great at this

#

j/k 😈 lol

naive pawn
#

you need to figure out how you want your economy to work, how it scales

amber spruce
#

true

#

but i think i made a mistake with the math because i wanted it to increase my 10% each time but after a certain point its over doubling each time

#
pancakePrice = pancakePrice + (pancakePrice * (pancakeValueUpgrade / 10));

this is the code/math for each upgrade

naive pawn
#

what's pancakgeValueUpgrade?

amber spruce
#

thats the variable that tracks how many upgrades you have done

naive pawn
#

if it should just increase 10%, that would just be pancakePrice = pancakePrice + pancakePrice / 10, or pancakePrice *= 1.1;

#

you're using the current value as a base, rather than the initial value

amber spruce
#

oh thanks

naive pawn
#

though, that would exacerbate your issue

#

if a geometric series is how you want your prices to scale, then your economy should be a little south of that same series

#

(if you have a single upgrade, that is; if you have multiple upgrades, you should make it drop off faster than prices)

hexed nymph
#

Yooo does anyone knows any tutorial or something to make a controller settings in unity?

#

Like change the input of something

naive pawn
hexed nymph
#

All the videos are for creating the main menu

#

And the creating settings menu video does not have the input settings

outer haven
#

Anyone here willing to have a look over my character controller if I tell them what's up? Been stuck at an issue for over 3 days, asked help in 3 different discords, asked help in 2 different reddits, asked several friends, asked 3 different AI's. I just cannot figure it out and I'm stuck.

#

I know having a look at an entire character controller is daunting. I could also send relevant parts. But seeing the entire code will probably give you the entire overview of it.

slender nymph
#

!ask

eternal falconBOT
slender nymph
#

read the last point in particular

outer haven
#

@slender nymph I already did send in my question before. See the thing I'm replying to. Perhaps I should've tagged it. Just don't have an answer to it yet. Had some helpful suggestions but they were far beyond my skill level (state machine design).

#

All I know is, when I remove the JumpBufferCounter and CoyoteTimer and set my jump to GetControlBinding() instead of GetControlBindingDown(), I can jump out of the water. But if I don't have those buffers and timers, you can infinitely hold spacebar and keep jumping on land.

rancid tinsel
#

In an observer pattern, how do you have the observers find the subject without coupling?

#

The only way I've found is something called a "Message Bus" but that is way overkill for what I'm doing

rich adder
#

the typical modes, DI, Singleton etc

rancid tinsel
#

Singleton is still coupling it

rich adder
#

its a 1 way reference though

#

nothing wrong with using that imo

rancid tinsel
#

I agree but ideally for this project I'd want to couple as little as possible

#

especially in the bits I'm "showing off"

#

ie patterns

rich adder
#

its not a tight coupling though

rancid tinsel
#

originally I didn't use observer at all and just did a C# action which was WAY simpler

rancid tinsel
#

so it iterates through it's observers, and notifies each of them

#

the issue is idk how to have the observers subscribe without coupling lol

rich adder
#

uhh isnt observer just using Events?

rancid tinsel
#

I don't think so, but I could not explain the difference if you asked me

#

I'll look into it

rich adder
#

it is, i think the only main difference is you typically DI the reference

#

create a bit more abstractions with interfaces n all

#

its jiust long winded way of saying "using events" and the Invoker doesnt care who listens

rancid tinsel
#

I think it may just be that the observer pattern is designed to work with OOP? So you make an observer object, rather than having an event carry the message

#

or something idk

#

idk if that makes sense

rich adder
#

its just this

rancid tinsel
#

yes

rich adder
#

yes just event observing

naive pawn
#

observer, pub/sub, and events are really the same thing

rich adder
#

DI is mostly whats used let the Observers recieve the Publisher

#

unless the event is static sometimes

rancid tinsel
#

I think the key difference is that you can have an Observer object, but you can't have an Event/Action object?

naive pawn
#

sure you can

#

Action is a type, which can have instances

rich adder
#

Observer is just a fancy word for events

rancid tinsel
#

but you can't have a monobehaviour action for example right?

rich adder
#

sure you can

#

monobehaviour is a T you can put any T in Action

rancid tinsel
#

no I meant

#

the action being a monobehaviour, not passing it

naive pawn
#

well in c#, no, i don't think so

#

but this is kind of a language detail

rancid tinsel
#

yeah its kind of semantics

naive pawn
#

for example in js, a function is an object with an internal slot, so you could make a function that also works as a monobehaviour
in java, the equivalent of "actions", lambdas, use interfaces, so you could have a class that otherwise acts as a monobehaviour but also implements Runnable

#

but the core of observer/pub-sub/events is just, it has a callback

#

you could have a wrapping object for any of those definitions, as an intermediate manager, if desired

#

but it's not necessary

hexed nymph
#

Yooo I want to call a variable (which is a KeyCode) from other script but it doesn't work

#

public System.DEFAULTmov movement;

public void Select(string name)
{
    if (name == "A")
    {
        movement.right = KeyCode.A;
    }
}
#

"DEFAULTmov" is the script that contains "right" as a variable

naive pawn
#

also for future reference, !code

eternal falconBOT
slender nymph
#

also note that unless you wrapped your class in the System namespace yourself it is definitely not in that namespace

rancid tinsel
#

do you show interfaces the same way you show inheritance in UML?

#

as in like this

slender nymph
#

that's not a unity question

atomic crater
#

Hello there. I tried to make it that a script references the object it's attaching. The script I use is for making the text fade out, but when I test it, it doesn't grab the object as the game starts, and I don't know what did I do wrong since there's no error.
https://paste.mod.gg/masrwycqerwr/0
I want to do it this way so I wouldn't have to reference it in editor or by name/tag. It'll just reference the thing it's on

atomic crater
obtuse pebble
# atomic crater

What if you put 'Debug.Log("A Value: " + aValue)' in the update function? What do you get as a result in the console? Does it decrease there?

atomic crater
#

That's not the problem. The problem is that the Text variable doesn't automatically get the reference object

obtuse pebble
#

Oops my bad. Maybe try to get TextMeshProUGUI as it is on the UI and not in the regular scene?

ivory bobcat
#

Or TMP_Text if you're uncertain

atomic crater
#

It works but the text doesn't fade out as the value decreases

obtuse pebble
ivory bobcat
#

If statement is likely false or fade rate may be zero in the inspector

ivory bobcat
atomic crater
#

I made active true and it doesn't make the text fade

#

The value changes, but it doesn't seem to do anything to the text itself

ivory bobcat
#

Do you ever apply the value to the text's alpha?

atomic crater
#

I should've. Line 19 has aValue set to text alpha

#

oh wait, I think I found a problem

ivory bobcat
#

You would need to apply that variable's value back to the text's alpha to modify the text's alpha value

obtuse pebble
#

Like Dalphat is saying, you are setting aValue to the value of the color. You need to do it the other way around, as you want to set the color value to the aValue.

ivory bobcat
#

It wouldn't because Start only occurs once

#

Just update the value after changing it in Update

atomic crater
#

It works now

#

Tho I don't know why I can't just set aValue to it directly as it said it's not a variable. I have to write "text.color = new Color(text.color.r,text.color.g,text.color.b,aValue);" to make it work.

#

I mean, if that's a c# way, I get it, I'm just curious why it doesn't work that way, and why I have to put "new" on Color

ivory bobcat
#

Color is a struct (value type). The property returns a copy of the color only.

#

You'd need to assign color an entirely new color to modify it as modifying the alpha of a copy from the getter will not modify the actual color on the tmp component.

ivory bobcat
atomic crater
toxic herald
#

Anyone here knows how to make recording cameras? like content warning does? i know few APIs, but they're all paid, is there any free option?

rich adder
naive pawn
toxic herald
# rich adder I havent played the game, but what exactly does recording do ? like a video ?

Yep, you basicaly use the video camera to record a video and save it at the game files
so, my goal was to make it when the player is using the camera, the player can record 15 seconds, and then after a cooldown he can record a little more
In my game you are basicaly in a team of reporters trying to prove the existence of ghosts, then you record and take pictures of proofs, to then manually create a headline for it, and choosing the best videos you made to add at the headline

rich adder
#

hmmm I wonder if something like Unity recorder has some type of inGame api

gleaming karma
#

Is this where you ask questions about coding?

rich adder
gleaming karma
#

oh lol

#

I just started coding and I am following this book and its showing errors in my code when following the book.

rich adder
#

look carefully at your Method declaration

#

the first red underlined is usually cause for the rest

gleaming karma
#

Ahhh I see it

rich adder
#

remember ; means end a statement, not very good thing when you're opening a code block/body after

gleaming karma
#

Gotcha, thankyou

frank solstice
#

hey uhh im making an end level thingy that takes you to the next scene but im getting an error here is my code

eternal falconBOT
rough lynx
rich adder
#

nice

frank solstice
#

im an idiot

rich adder
#

and this is why we share code with Links/Codeblcok and not screenshots

frank solstice
#

thanks so much

rough lynx
#

But please do follow nav's advice

rich adder
#

got me good

rough lynx
#

If you configured your ide it would've told you that namespace didn't exist

rich adder
#

yeah it would underline it red

#

make sure you have a configured IDE its also required to get help here next time

frank solstice
#

i didnt know you had to configure ill do it now thanks!

rich adder
#

your sanity will thank you

rough lynx
#

No worries best of luck

#

Lol yeah

frank solstice
#

i hope so especially sicnce i hate spelling on pc and capitalisation😭

rich adder
lilac root
#

could anybody offer me some help rq with the animator panel? im tryna use a simple ai wandering script but the animal never enters the idle state or the idle animation.

rich adder
#

you mentioned the problem in a way, but we cannot see anything you've done, setup or code . We can only do random guesses, not very useful lol

lilac root
#

thats my script but i think its mainly the animators problem

#

since i just took these from online

rich adder
#

👇

eternal falconBOT
lilac root
rich adder
lilac root
rich adder
# lilac root

so its going into Run but doesnt come back into idle ?

lilac root
#

yeah

rich adder
#

Debug.Log the part of the code where it supposed to hit the
animator.SetBool("isRunning", false);

#

for good measure I'd also remove this 👇

#

and also you should observe the animator while selected (select gameobject with animator) to see what the transitions are doing

lilac root
rich adder
#

yes I understand the problem, but you have to figure out why

#

first step would be debug.log

#

looking at the animator would also show you if the bool was ever triggered once

lilac root
rich adder
#

tutorial is fine if it works and you can follow it exactly.

#

but imo you should do the structured Unity courses first in !learn site

eternal falconBOT
#

:teacher: Unity Learn ↗

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

rich adder
#

they cover everything a bit more clear because well they made the software lol

grand snow
#

nah some rando youtube video must be better! /s

mighty cosmos
#

is invoke no longer used? Edit:nvm me

lilac root
rich adder
tulip stag
#

What's the best variable type to store and display a table like this? it must be dynamic, as different instances of the class will have different collumns on the table

slender nymph
#

a list of some custom object that has the properties you want on it

mighty cosmos
tulip stag
slender nymph
#

i mean exactly what i said. you create some type that contains the properties you want to represent the columnds of your table and you just create a list of that

tulip stag
#

Oh, ok, but I don't think that works. Each instance of the class will have tables with different collumns

amber spruce
#

hey so i have a scriptable object (i think thats what its called) and i want to during the game change one of the values but for some reason its saving it

pancakeData.Delay = Mathf.Max(pancakeData.Delay * 0.90f, 0.1f);

is there a different way to code it or smth so it doesnt save the new value

slender nymph
tulip stag
#

I can have an instance of my class class called Cleric with a table that has the collumns Level, PB, Features, Channel Divnity and Spell Slots 1-9. Rogue on the other hand would have a table with the collumns Levels, PB, Features and Sneak Attack Die. etc

amber spruce
slender nymph
#

yeah, or just in the editor instantiate a clone of the SO and use that in its place

toxic pine
#

hello i was wondering if it was worth it to follow this tutorial to make a radar chart or if i should use a line renderer wich would be easyer and faster i think; https://youtu.be/twjMW7CxIKk?si=gcMT9-aq7TTL4RVN
YouTube

✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=twjMW7CxIKk
Let's make a Radar Chart as used in RPGs to display Character Stats.

We're going to create a very nice clean Stats class and a script to display it. It will be shown using a custom Dynamic Mesh drawn in the UI.
The code is very easy to modify to add mor...

▶ Play video
eternal needle
toxic herald
rich adder
#

a series of pictures

#

have you tried to use ffmpegout before assuming there is a big performance impact ?

toxic herald
#

It worked, but the performance was like cut in more than half, I was getting 80 fps in a 3070, where I used to get 340

grand snow
#

how were frames captured and sent to ffmpeg?

rich adder
# toxic herald

bummer. there are probably other solutions, haven't looked too deep into it

toxic herald
grand snow
#

i was wondering what the perf was and how it was done incase it could be improved. ffmpeg offer native libs which should be used

toxic herald
#

Cause it's kinda just a sequence of screenshots

grand snow
#

ngl i dont know how to record sound "playing" in unity unless an audio listener can output its current state

rich adder
#

maybe you need to look into fmod or wwise

#

NAudio could also be an option

toxic herald
#

Well chat gpt told me content warning used videokit

rich adder
#

50$ a month is insane

toxic herald
#

Even more for an solo indie dev

grand snow
#

why is this a subscription

rich adder
#

what isnt a subscription these days..

toxic herald
rich adder
#

garbage model

#

everyone took from adobe's greed

toxic herald
#

If only it was a one time buy

#

Like an unity asset

grand snow
#

well i suspect such a package isnt super secure 😉

toxic herald
#

Well it needs an access key so catcrymic

grand snow
#

imagine if its always checking at runtime if you have a subscription still and breaks ur game when you stop

toxic herald
grand snow
#

yea thats mental id never ever use such a thing

toxic herald
#

Yeah, I'd even pay 150 dollars for it, if it was an asset or something

#

But monthly subscription? Hell nah, that's the reason I never played wow lmao

eternal needle
#

you also asked a spam generator what tool a game uses. maybe just try contacting the game developers themselves and ask

rich adder
#

more likely it is a custom solution

#

if you know what you're doing with external libraries, you can get this done

eternal needle
#

even just skimming through, it doesnt seem like this is all that impossible to write yourself

rich adder
#

or perhaps wrong settings were chosen

toxic herald
rich adder
#

kinda curious to try this myself later, see what i can cook

toxic herald
#

Sad part is that this is probably one of the 2 core mechanics of the game so I really need to get this right lol

grand snow
#

in an ideal world you can capture and stream frames directly to be encoded

toxic herald
grand snow
#

try but expect it to make up shit

#

its common with these good c/cpp libs that their documentation is trash and soo hard to read

#

(libcrypto im looking at you ✊ )

rich adder
toxic herald
#

Yeah, thats why gpt is most likely my last resource lmao

void thicket
#

Search for some open source that uses it on Github

grand snow
polar dust
#

Surely there's something that lets you capture a bunch of frames from a camera, then you can stitch those together with ffmpeg

toxic herald
#

I wish I had contact with any devs of content warning but I can't even find they twitter lmao, only the publisher

grand snow
#

hope you can figure out something but plz try to use the lib instead of writing files to disk and invoking ffmpeg as a process many times

toxic herald
toxic herald
#

Oh I see why it's a subscription, apparently they offer you an option to save your videos on cloud, but why wouldn't they allow you to even save videos at the own project files at the free option, you can't do anything lmao

#

And also some ai bs

ashen wind
#

Hey I want to display rare unicode charcters in unity

#

I figure the best way to do this is to import a font

#

since just putting the unicode character in the string in script doesn't seem to work for the rare ones

#

but I have no idea how to make a font

#

like this kind of thing

#

but arbitrary unicode characters so I can mix and match them programatically

calm adder
#

!code

eternal falconBOT
calm adder
#

i need help with this piece of code

obtuse pebble
calm adder
#

i found the bug but im not sure how to solve it using an AND.

calm adder
#

you can use stamina and everything just fine however you'll never regain it until you make IsStaminaBeingUsed false which is impossible unless you get your stamina to 0 which isnt what i want

#

i want it so you regain if you just let go of shift which is what i have set up

#

-# Also its Line 111 - 123

#

@obtuse pebble

obtuse pebble
#

"if (stamina <= maxStamina)" So you will be recharging stamina even if it is equal to max stamina. I am assuming this is not intentional?

calm adder
obtuse pebble
#

Alright, I am pretty new myself, but I don't see you ever setting isStaminaBeingUsed to true.

calm adder
#

because everything seems to be fine its only that one bug with never being able to regain without reach 0 stamina

mighty cosmos
#

why does this not work? i'm sure i'm doing everything correctly

calm adder
mighty cosmos
#

well i can only jump once, I'm not getting the debugs of the Ground Hit, or the Jump available either.

#

i want to make sure i cannot jump before i hit the ground

calm adder
#

it must be the exact spelling

mighty cosmos
#

but i'm not getting the ground hit debug

calm adder
#

Oh

mighty cosmos
#

which is out of the if statement

obtuse pebble
#

I doubt it's the tag, as the "hit ground" debug log does not trigger either

calm adder
#

i see now

mighty cosmos
#

yes

eternal needle
#

you're using OnTriggerEnter, which implies the colldier is a trigger

calm adder
mighty cosmos
#

oh ffs

calm adder
#

you can either use OnTrigger or OnCollision Enter

mighty cosmos
#

OnCollisionEnter is what im supposed to use ye

calm adder
#

but for on trigger double check that it has IsTrigger = true

eternal needle
#

and your colliders likely shouldnt be triggers for this

calm adder
mighty cosmos
#

alright thank you, OnCollisionEnter was the correct function to use. it works now. sorry about begin blind xd

calm adder
#

idk

calm adder
mighty cosmos
vague sequoia
#

The Item Assets script shows me null and I don't know why, I'm trying to spawn an object but it always shows me that ItemAssets is null and I don't understand why.```using UnityEditor;
using UnityEngine;

public class ItemAssets : MonoBehaviour
{
public static ItemAssets Instance { get; private set; }

[Header("ItemModels")]
public GameObject PfSword;
public GameObject PfAxe;
public GameObject PfLance;

[Header("ItemImages")]

public Sprite SwordImage;
public Sprite AxeImage;
public Sprite LanceImage;

   private void Awake()
{
    if (Instance == null)


    {
        Instance = this;
    }
    else
    {
        Debug.LogWarning("Hay más de una instancia de ItemAssets en la escena.");
        Destroy(gameObject);
    }
}
eternal needle
calm adder
eternal needle
eternal needle
mighty cosmos
eternal needle
#

why are you replying to my message on that? and also their problem is not advanced at all

#

its really quite beginner

eternal needle
calm adder
#

My unity just Crashed... Turns out you should never write a while loop before checking that its not gonna run indefinitely

eternal needle
#

!code

eternal falconBOT
eternal needle
#

please delete those and use a link to paste it

#

also that first code isnt even valid c# so maybe check if u have compile errors first

vague sequoia
#

aaa ok should I upload them as a file?

eternal needle
#

read the bot message, and even my message below it... "use a link to paste it"

#

there is the large code block section

vague sequoia
void thicket
vague sequoia
void thicket
#

Taking screenshot is just.. missing whole point

eternal needle
# vague sequoia https://paste.mod.gg/ceaimmpjbuwl/0

none of these methods use unitys methods like update, so something must be calling these. Try to follow down the path of whats calling SpawnItemWorld, because you're likely doing this during or before awake

#

your problem is just this code is running before ItemAssets.Awake is running

vague sequoia
vague sequoia
sour fulcrum
#

I should probably put this in general but theres an active convo in there that i don't wanna disrupt

I have a custom generic class called ExtendedMatrix2D<T> which is basically a T[,] with a bunch of helper functions built into it.

I have a ExtendedMatrix2D<ScriptableTile> instance and a function requesting a ExtendedMatrix2D<ScriptableContent>.
ScriptableTile derives from ScriptableContent but when I attempted to pass in my ExtendedMatrix2D<ScriptableTile> to implicitly downcast it it doesn't like it.

Is there any way I can support this kind of implicit downcasting of my ExtendedMatrix2D or is that not really how this is supposed to work

#

(the line in particular for example)

protected override ExtendedMatrix2D<ScriptableContent> GetMatrix() => currentLayout != null ? currentLayout.TileMatrix : null;
naive pawn
sour fulcrum
#

Yeah I get why it's happening but just curious how I should go about handling this

naive pawn
#

make the function generic, perhaps

#

since it can work on multiple types, apparently

sour fulcrum
#

It is generic, just currently defined as ScriptableContent. I'd ideally prefer to downcast it like im trying to in this context but if that's not how i should be handling this kind of thing im open to pivoting

#

(as i wanna use more deriving types and it doesn't need to be anything more than a scriptablecontent for this stuff)

#

was hoping there was some cool c# magic i could implement into ExtendedMatrix2D to instruct it on how to downcast stuff ezpzily

naive pawn
#

generic classes are invariant in c#

#

for T ≠ U, A<T> is not assignable/a subtype of A<U>

#

so downcasting the generic won't work

#

ExtendedMatrix2D<ScriptableTile> and ExtendedMatrxi2D<ScriptableContent> are disjoint types, so if your function should handle both, then it should be generic

slender nymph
#

ah wait, i don't think that applies. I assumed you were having trouble with changing the return type for your overridden method which is what covariant return types is referring to. Chris is right here that the generic class is invariant

#

depending on your actual needs with this you could create a generic interface that supports covariance and use that for the variable that you are assigning to

sour fulcrum
#

i see i see

#

I tried being big brain and making that function generic in a way where the implementation of this function defines the constraint rather than the generic in the function directly but no dice there either

protected abstract ExtendedMatrix2D<A> GetMatrix<A>() where A : T;
#

im sure it makes sense but i do not like when VS tells me this aha

naive pawn
#

wait hold on what are you trying to do here?

#

this is a method on the extended matrix class?

#

and you're trying to get this as a different type?

sour fulcrum
#

There's a lot going on here, wasn't sure how much I needed to provide.

I have a ScriptableRoomLayout class that contains a couple ExtendedMatrix2D's including ScriptableContent, ScriptableTile and ScriptableEntity matrixes.

right now im trying to use them in a custom EditorWindow which is a TileMapEditor<T> that I want to generically handle rendering and modifying 2d arrays.

This TileMapEditor<T> stores a reference to the ExtendedMatrix2D it's targeting which it's provided by an abstract class (in this case ScriptableContentEditor : TileMapEditor<T>

#

I guess i probably don't need to store the defined matrix in TileMapEditor though and can probably just rely on constantly asking for it via a property or something

#

which frees me up abit

#

maybe

#

i think ive maybe rubber ducked myself a little

brazen cedar
#

Hello, so I was following a tutorial for a pickup system that was made for Unity 2022 and I'm using Unity 6, the problem is that the script doesn't work, i have re-written it, changed some variables and options, added debugs and can't find a reason to why it doesn't work

#

I have also made an exact same version with the new input system and still has the same issue

#

Maybe something about the Rigidbody or forces changed in Unity 6

exotic jacinth
#

hey everyone, I am new to unity and I am facing a problem,

I have several tutorial popups, dialogues, and map triggers in my game that should appear every time the game starts fresh but should not reappear after the player dies and restarts.

Current Issues:
When I first start the game, all dialogues, popups, and map triggers appear as expected.

After the player dies and restarts the game (without closing it), these dialogues and popups do not appear again(working fine).

If I fully close and reopen the game, the dialogues and popups should appear again (this is not working ).

how can i fix this please?

slender nymph
eternal falconBOT
exotic jacinth
#
using UnityEngine;

public class GameStartManager : MonoBehaviour
{
    void Awake()
    {
        
        if (!PlayerPrefs.HasKey("GameLaunched"))
        {
            PlayerPrefs.SetInt("GameLaunched", 1); 
            ResetTutorialData(); 
        }
    }

    void ResetTutorialData()
    {
        Debug.Log("Resetting tutorial state...");
        PlayerPrefs.DeleteKey("HasSeenPopups");
        PlayerPrefs.DeleteKey("HasTriggeredMap");
        PlayerPrefs.Save(); 
    }
}
#
private void OnApplicationQuit()
{
    PlayerPrefs.DeleteKey("GameLaunched");
}
rich adder
exotic jacinth
#

so if I build the game and run then it will work ?

rich adder
#

it should delete the key

#

mobile has a few caveats

exotic jacinth
#

and if I use alt+f4 to close the game will it call onApplicationQuit()?

rich adder
#

I think so.. one way to be sure tryitandsee

slender nymph
rich adder
#

yea playerprefs is overkill and overcomplicating it

slender nymph
#

If you have domain reload disabled then you just need to reset the static variables as normal in that workflow. Otherwise they will be reset each time you play

keen owl
#

I believe a static bool would work in that scenario... at least what I use for my loading screen

naive pawn
# brazen cedar

what's the issue? we can't help much if we don't know what to fix

exotic jacinth
# slender nymph You don't need player prefs for any of this. Just use a static variable
using UnityEngine;

public class TutorialPopup : MonoBehaviour
{
    [SerializeField] GameObject popupPanel;
    [SerializeField] MovePlayer movePlayer;
    [SerializeField] LookMouse lookMouse;
    [SerializeField] GameObject canvas;

    private static bool hasSeenTutorial = false;

    void Start()
    {
        if (hasSeenTutorial)
        {
            popupPanel.SetActive(false);
            movePlayer.enabled = true;
            lookMouse.enabled = true;
            canvas.SetActive(true);
            lookMouse.LockCursor(true);
            return;
        }

        
        popupPanel.SetActive(true);
        movePlayer.enabled = false;
        lookMouse.enabled = false;
        canvas.SetActive(false);
        lookMouse.LockCursor(false);
    }

    public void CloseButton()
    {
        movePlayer.enabled = true;
        lookMouse.enabled = true;
        canvas.SetActive(true);
        popupPanel.SetActive(false);
        lookMouse.LockCursor(true);
        hasSeenTutorial = true;
    }
}

like this?

nocturne oak
#

Hey yall. This is probably a pretty simple question. As the code reads, I am trying to get the child of a gameobject with the selected tag. I dont really understand what the shown error means. Could someone explain the error, and or how to fix it?

keen owl
nocturne oak
#

Like such?

keen owl
nocturne oak
#

ah ok

#

ohh, that makes sense. Thank you my friend

grand badger
# keen owl well you'd need to add .gameObject at the end I believe

@nocturne oak yeah you can think about it like this:

Game-wise:

  • Scene is a snapshot of a "world" at a specific time
  • GameObject is an object that resides in the Scene
  • Components define a GameObject's properties and behaviour in the Scene
  • All Components attached to a GameObject are part of the same object

Code-wise:

  • Each of [GameObject, Transform, Components] are different objects (in the PC's RAM).
  • Transform is a Component that allows the engine to grab the GameObject's location.
  • When you wanna cache/store a reference to a variable of type GameObject, you can't assign its Transform, because they're different objects.
keen cargo
#

@exotic jacinth also you can make it so that the onapplicationexit works in the editor too, i think it's a preprocessor directive + an extra line of code, look it up you'll find it easily

runic quartz
#

hello all, i have an issue with colliders.
I have a set of interactions that require the player capsule collider to have isTrigger = True. I have also been putting the Freeze Position.y = True as well up to this point. Now i want to implement a jump mechanic. When I set FreezePosition.y = false the player falls through the platform, ignoring the platform's box collider.

Can anyone help in implementing the jump mechanic? Please let me know if any information is missing

#
public bool inAir = false;

void OnCollisionStay(Collision collision){
    if(collision.gameObject.CompareTag("GroundTag")){
        if(Input.GetKeyDown(KeyCode.Space) && inAir == false){
            playerRB.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
            inAir = true;
        }

        inAir = false;
    }

}
north kiln
runic quartz
#

yes that was the issue. I did find a workaround by using two different colldiers - a capsule collider to handle the trigger interactions and a box collider to detect ground collision. Works now

runic quartz
bright hull
#

`private void AttackPlayer()
{
agent.SetDestination(transform.position);

Vector3 directionToPlayer = player.position - transform.position; 
directionToPlayer.y = 0; 
transform.rotation = Quaternion.LookRotation(directionToPlayer);

if (!alreadyAttacked)
{
   
    Rigidbody rb = Instantiate(projectile, transform.position, Quaternion.identity).GetComponent<Rigidbody>();

    
    Vector3 shootDirection = (player.position - transform.position).normalized; 
    rb.AddForce(shootDirection * 32f, ForceMode.Impulse); 

    rb.AddForce(transform.up * 5f, ForceMode.Impulse); 

    alreadyAttacked = true;
    Invoke(nameof(ResetAttack), timeBetweenAttacks);
}

`

Enemy's bullets going up instead of going to player. I think it's about math and I'm not good at it. Can someone help me?

zenith crown
#

Hey im currently working on isometric movement i was wondering if anyone here also had it and could help me with it

bright hull
zenith crown
#

When i press W or S the player moves forward or backwards diagonally (North-West, South-East) and for A and D it moves along the other diagonal (North-East, South-West) instead of moving up, down and side to side

#

Basically shifted 45 degrees counter clockwise

bright hull
#

Can you send codes?

zenith crown
#

Yes one second

#

And heres how the camera is setup

bright hull
#

`void Move() {
// Convert local input to world space
Vector3 movement = transform.TransformDirection(input) * speed * Time.fixedDeltaTime;

// Move the player based on the calculated movement
rbody.MovePosition(transform.position + movement);

}
`

#

Change Move function.

#

to this.

#

This is because you use the input vector directly in the global domain (world).

zenith crown
#

Ohh okay

#

Thank you

bright hull
#

Anytime.

zenith crown
#

I now am encountering issues with uneven speeds. When 2 keys are held down the speed is faster than when one is pressed down.

feral moon
#

Can you tell me where to attach the script in the timeline, on this track?

grand snow
verbal dome
zenith crown
#

Thank you

queen adder
#

Does anyone know how to use this ?

trail heart
# queen adder Does anyone know how to use this ?

It appears you're meant to use Animator.SetTrigger method to call animation states that correspond to the trigger parameters
This is not how animator controllers are meant to be set up, as there's no advantage to using one like that at all, but it should work

queen adder
frank beacon
trail heart
trail heart
# queen adder Okay, thanks.

Also when you find third party tutorials for the Animator, you unfortunately have to be skeptical about them
A lot of them are made by people who never fully understood the system and instead recommend you operate it with custom code that unnecessarily recreates the state machine and transition functionality that already exists
Prefer the documentation and Unity's official tutorials as your primary source

fervent abyss
#

how can i wait 1 frame in coroutine?

wintry quarry
rancid tinsel
naive pawn
rancid tinsel
#

yielding null has additional time between frames?

wintry quarry
rancid tinsel
# naive pawn

oh so it waits until the frame is "shown", and yield null waits until the next update call?

low warren
#

hi
where can i ask a question about the debug draw mode in the unity editor?

low warren
frank beacon
low warren
#

i don't know 3d but could you please tell me what did you do?

low warren
#

then why is he dancing😆

#

alrgiht never mind

frank beacon
#

idle

low warren
#

can you give me the code?

frank beacon
#

ok

low warren
#

i don't understand it that much but maybe that will help me

#

to say something

frank beacon
#

maybe its because the ragdollcontroller

low warren
#

what is a ragdollcontroller?

#

the thing that makes the player moves?

frank beacon
#

no

low warren
#

okay then idk
i have never heard that word in my life
"ragdollcontroller"
IDK sorry

low warren
frank beacon
#

i dont know about 2d ssry

low warren
#

no i mean where can i ask it in this server

frank beacon
naive pawn
#

@frank beacon what's your question

low warren
frank beacon
#

why does it fly

naive pawn
#

a video is far too little info to go off of

#

what do you have controlling the position of that object?

frank beacon
#

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

public class ragdollControl : MonoBehaviour
{
private BoxCollider mainCollider;
private Animator anim;

Collider[] ragdollColliders;
Rigidbody[] ragdollRB;
 void Start()
{
   mainCollider = GetComponent<BoxCollider>(); 
   anim = GetComponent<Animator>();

   ragdollParts();
   RagdollOFF();
}

 void RagdollON()
 {
    anim.enabled =false;
             foreach(Collider c in ragdollColliders)
     {
         c.enabled =true;
     }
     foreach(Rigidbody rb in ragdollRB)
     {
         rb.isKinematic =false;
     }

     mainCollider.enabled =false;
     GetComponent<Rigidbody>().isKinematic = true;
 }

 void RagdollOFF()
 {
     foreach(Collider c in ragdollColliders)
     {
         c.enabled =false;
     }
     foreach(Rigidbody rb in ragdollRB)
     {
         rb.isKinematic =true;
     }

     mainCollider.enabled =true;
     anim.enabled = true;
     GetComponent<Rigidbody>().isKinematic = false;
 }
  private void OnCollisionEnter(Collision collision)
 {
     if (collision.gameObject.tag == "colisionador")
     {
          RagdollON();
     }
 }
 void ragdollParts()
 {
      ragdollColliders = GetComponentsInChildren<Collider>();
      ragdollRB = GetComponentsInChildren<Rigidbody>();
 }

}

#

i think

eternal falconBOT
naive pawn
#

there's nothing here that controls the position of the object though

frank beacon
#

oh

naive pawn
#

does your animationclip change the position or something

frank beacon
#

no

#

i fixed it i gave it 100 mass and now it doesnt fly

crystal kindle
#
using UnityEngine;
using TMPro;

public class Movement : MonoBehaviour
{

    public Rigidbody rb;
    public float Walkforce;
    public float Climbforce;
    public float Descendforce;
    public TMP_Text TimerText;
    public TMP_Text SpeedText;
    private float playerSpeed;
    private bool isTimerRunning = false;
    private float TimerTime = 0.00f;

    void FixedUpdate() {
        if (Input.GetKey("a")) {
            rb.AddForce(-Walkforce, 0, 0);
            isTimerRunning = true;
        }

        if (Input.GetKey("d")) {
            rb.AddForce(Walkforce, 0, 0);
            isTimerRunning = true;
        }

        if (Input.GetKey("w")) {
            rb.AddForce(0, Climbforce, 0);
            isTimerRunning = true;
        }

        if (Input.GetKey("s")) {
            rb.AddForce(0, -Descendforce, 0);
            isTimerRunning = true;
        }
        
        if (Input.GetKey("m")) {
            isTimerRunning = false;
            TimerTime = 0.00f;
        }

        if (isTimerRunning == true) {
            TimerTime += Time.fixedDeltaTime;
        }

        playerSpeed = Mathf.Abs(rb.linearVelocity.z);
        Debug.Log(playerSpeed);

        TimerText.text = "Time - " + TimerTime.ToString("F2");
        SpeedText.text = "Speed - " + playerSpeed.ToString("F2");
    }
}

guys why is playerSpeed 0 when the cube is moving?
all the script works so it's not an issue, but playerSpeed is 0, thus SpeedText is 0, please help

wintry quarry
#

You probably want linearVelocity.magnitude

crystal kindle
#

oh okay, thank you very much! i wont crosspost from now on

grand snow
#

any good tutorial should do this anyway

crystal kindle
grand snow
forest jewel
#

Hello everyone!

ashen wind
#

can someone help me understand aspect ratios in unity?

eternal falconBOT
naive pawn
#

especially that last point

ashen wind
#

I positioned my UI based on the 1920x1080 aspect ratio

naive pawn
#

er that's a resolution, not an aspect ratio

#

(you sure this is a code question?)

ashen wind
#

yeah one sec

#

trying to get a screenshot

#

but then when I build for PC or WebGL all the UI is messed up and in a different location

#

the health bars got really tiny, and the bottom boxes aren't even visible

slender nymph
#

Read the documentation pinned in#📲┃ui-ux to learn how to correctly anchor and scale your ui

fervent abyss
#

how do i set layer mask to "nothing"? when i try to set it to 0 it sets it to default

rocky canyon
#

once u have ur layout laid out.. grab the window and do some squeezy streetchy

rich adder
#

you cannot change the default layers

rocky canyon
fervent abyss
#

im trying to set a layer to nothign in code

fervent abyss
ashen wind
rocky canyon
naive pawn
fervent abyss
rocky canyon
#

if ur wanting Nothing why even use a layermask at that point? lol

#

culd just use a boolean...
ifUseLayerMask == true -> now use the layermask
ifUseLayerMask == false -> just use code w/o a layermask

ashen wind
# rocky canyon yea.. if its stretching everything ur anchors are bad

I'm still not sure I understand. I changed all the anchors of the rect transforms so none of them were stretch and then I put the canvas to scale with screen size and it still put them off screen and stretched them, so I changed them again and built and it's exactly the same as it was

rocky canyon
#

are u anchoring them to the center?

ashen wind
#

how do I anchor them so that their positions on the screen are fixed

rocky canyon
#

u should anchor to whichever corner is closer..

ashen wind
#

is this wrong?

rocky canyon
#

and how its setup in heirachy.. anywho ^ like here.. the UI i have in the bottm left.. well, it should be anchored to the bottom left.. (its offsets are left and bottom)

#

for the branding logo its top right.. soo ih ave it anchored top right.. w/ its offsets being from the right and the top

#

etc etc

ashen wind
#

take these two health bars that are supposed to be in the top left

#

when I build like this, they are extremely tiny suddenly

#

and they're closer to the center than the left

#

even though I selected top left in my anchors

rocky canyon
ashen wind
#

then why do they change size in the built version?

#

and move from their position in the corner?

#

in unity

#

in build

rocky canyon
#

well its Rference resolution is 800x600..

ashen wind
#

ohhhhhhhh

rocky canyon
#

u want to keep them all the same

#

to have consistent results 😉

mental flame
#

I installed URP into my project, assiged URP pipline asset. I created a standard surface shader, but when I open it it is all errors. How do I make coding a shader compatible with URP?

rocky canyon
#

u find out u let me know 👍 ..

#

i typically end up trying to convert them to Shader-graph

#

with hit or miss results

mental flame
#

I made a shader graph and it isnt compatible

rocky canyon
ashen wind
#

is it something to do with one of the other settings like screen match mode?

rocky canyon
ashen wind
#

thanks

rocky canyon
#

good luck..

grand snow
#

urp lit shaders are a pain to do customly, use shader graph as much as possible

naive pawn
zenith crown
#

Oh right sorry

ashen wind
#

@rocky canyon bro i'm trippin. the build was using the wrong scene file. thanks for your help, your explanation fixed it

rocky canyon
#

jeez..

rocky canyon
queen adder
#

why is my vs code not showing any options like in the tutorials

slender nymph
#

!ide
also the tutorial is using visual studio not vs code

eternal falconBOT
rich adder
queen adder
#

tysm i'll try

plucky dove
#

how do y'all learning to code 😭 i just cant wtf

rich adder
naive pawn
#

there are resources in the pins

rancid tinsel
#

Does Unity use the flyweight pattern "by default"? Like when you assign a reference to a prefab and instantiate based on it?

#

Or do I not understand it correctly

rocky canyon
#

When you assign a reference to a prefab and instantiate it, Unity creates a completely new instance in memory. Each instance has its own copy of all data and components, so it doesn't automatically share memory the way a strict Flyweight pattern would.

#

Unity does do optimizations that resemble in it certain cases..

  • meshs, textures, and materials are shared ie. Multiple tree's using the same MeshRenderer will not duplicate the mesh data in memory..
  • scriptable objects sorta act like flyweights.. ie. can store shared data that multiple GameObjects reference w/o duplication
  • object pooling ie. object pooling achieves a similar effect by resusing objects instead of constantly creating/destroying them..
gilded canyon
#

how would i go about making an throwable that goes through the enemy but still registers as a hit and isnt trigger(so it can interact with the scene)

#

also i cant destroy the enemy onhit because of a death animation

wintry quarry
#

Use layer based collisions to set up the interactions

gilded canyon
#

wouldn't layer collision mean that the enemy throwable interaction is ignored?

wintry quarry
#

I'm not sure what the enemy throwable interaction is exactly

gilded canyon
#

so it shouldnt bounce off the enemy like any other prop

gilded canyon
forest jewel
#

I'm new to programming on unity, does anyone have tips on starting?

slender nymph
#

there are beginner c# courses pinned in this channel and the pathways on the unity !learn site will teach you how to use the engine

eternal falconBOT
#

:teacher: Unity Learn ↗

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

mighty cosmos
#

a question what's wrong in these pieces of code? after hitting the object or triggering it which has the first picture script on it. i'm able to jump but only once

slender nymph
#
  1. !code 👇
  2. where do you change the value of isGrounded
eternal falconBOT
mighty cosmos
#

without the canjump, the code works though

#

oh and i do change it

#

that's the last piece of code, ig i should have shown all the ones instead

naive pawn
slender nymph
mighty cosmos
#

alright, i will keep that in mind for the future but for my problem atm that's all of the code

naive pawn
#

share your code as text

slender nymph
#

the full class

naive pawn
#

!screenshots

eternal falconBOT
#

mad No

Be mindful, if someone requests your code as text, don't send a screenshot!

mighty cosmos
slender nymph
#

last time i checked isGrounded is not canJump

naive pawn
#

send your code as text.

mighty cosmos
slender nymph
#

use your IDE to find all references to that canJump variable since you claim that without that variable it works correctly

mighty cosmos
#

i have 3 references yes

viral stag
#

Hi guys in my game I made I have text in the top right corner but when I build the game and play it the text goes more to the middle and is not in the spot where it was like in the editor anymore. Any tips to fix taht please?

slender nymph
mighty cosmos
#

when i first make it public bool canJump = false;

slender nymph
#

then it should work with or without the canJump variable because that wouldn't be the issue

rare basin
slender nymph
#

documentation pinned in #📲┃ui-ux will cover how to anchor and scale UI for different resolutions/aspect ratios

mighty cosmos
#

okay, i saw the problem, since i'm working in scene 2 and had made a ground prefab before making scene 2 it didn't have the tags correctly. my bad

slender nymph
#

then how tf did you come to the conclusion that without the canJump variable it works?

mighty cosmos
#

i was testing in scene 1 😭

#

man i started learning unity like 3 days ago so mb few things still confuse me

nocturne oak
queen adder
#

it worked fine before i put in the images but now it's not responding(not going to the game), tysm

sour fulcrum
rich adder
#

your Image / panel is covering the buttons or BG cant tell from hierarchy if its in canvas lol

#

anyway in UI hierarchy is the order of rendering, Last = OnTop

queen adder
#

tysm

humble marsh
#

This is so confusing, i have this code

public static List<Vector2> pointsAt45DegreeAngles(Vector2 center, float radius) {

    List<Vector2> points = new List<Vector2>();

    for (int angleDegrees = 0; angleDegrees < 360; angleDegrees += 45) {

        float angleRadians = angleDegrees * Mathf.Deg2Rad;


        float x =   radius * Mathf.Cos(angleRadians);
        float y = radius * Mathf.Sin(angleRadians);

        
        points.Add(new Vector2(x, y));

    }


    return points;


}```
when i read the code after  i get this, why? its just a simple 0 to 360 degree cos / sine wave, why is this so confusing
#

i should get 1, .5, 0, -.5, -1, not .71 and -.71 (Input radius is exactly 1)

verbal dome
#

Isn't that how it's supposed to work

#

Vector of (1, 0.5) would have a magnitude of more than 1

humble marsh
#

but you can have a vector of 15 and 260 and its still good

verbal dome
#

Don't know what you mean by that

slender nymph
humble marsh
#

I'm saying, for the purpose of getting the sine / cos wave of a circle, shouldnt the output be (1,0), (.5, .5), (0, 1), (-.5, .5) (-1, 0)

north kiln
humble marsh
#

so if i input into a vector(.5, .5) i get a vector with (.71, .71)?

wintry quarry
#

But you're not ever at any time getting .5,.5

humble marsh
#

why am i not get .5 on a sin wave, doesnt it intersect .5 at 45?

earnest wind
humble marsh
#

i take the values from the sin / cos waves, and then create a vector2, i dont ever combine them before setting the vector 2 x / y components.

north kiln
#

We know

#

A circle of a radius 1 is never going to intersect with the points at 0.5, 0.5

earnest wind
#

logically the dragging line should be exactly aligned with the line you are dragging, basically in the example it should be the same as blue, but since i probably made a mistake where we calculate it based on mouse and camera thats probably why on certain angles it does this

Also ping me, thanks

humble marsh
#

thank you all for the help, i uh, need to relearn how a circle works. i needed a diamond in code, but tried to use a circle to define the points on the diamond.

eternal needle
# earnest wind

for stuff like this, i really suggest just using Debug.DrawLine or DrawRay to actually visualize what the vectors are at each step. Some of these things are kinda hard to look at code wise and tell you if some math is off.

#

if any vector doesnt align with what you think it should be, at least you have a starting place to confirm your math. otherwise its just you're doing 50 calculations and one is wrong

earnest wind
eternal needle
earnest wind
#

thanks

pure kite
#

HOW do I make a frame independent lerp, tryna smooth my camera but the speed keeps changing based on framerate

slender nymph
#

alternatively, if you are lerping a Vector3 you can probably swap to MoveTowards instead of Lerp if you just want to specify a speed instead of a percentage

verbal dome
#

SmoothDamp is also an option depending on what kind of smoothing you want