#💻┃code-beginner

1 messages · Page 725 of 1

rich adder
#

strange, maybe on the event system you can see whats being detected if any at all, new one kinda sucks at telling you whats happening only tells you on click

#

rigidbody (kinematic I think) or translate, each has its pros and cons
if you mean timescale you can use unscaledDelta

plush chasm
#

I think... my game window was bugged. I closed "game" and "device simulator" and reopened "game" and now everything seems to be working.

rich adder
#

as long as its working now though ig lol

silver fern
rugged ledge
#

Thanks, this worked.
The animation of my character is slightly skewed though, so when I walk forwards it actually ends up walking about 20 degrees off from 12 o'clock

wintry quarry
#

it could be an issue with how your scene/control system is setup or it could be an issue with your character model

plush chasm
rugged ledge
#

This is when holding W (ignore the random things in the scene, I'm doing some practice stuff for class)

rich adder
rugged ledge
#

The character does rotate with the camera, but it's off

#

And it's the animation itself that moves the character, not any script I've made (which I don't like, but that's what we were taught thus far)

rich adder
silver fern
rich adder
silver fern
rich adder
#

sprite editor lets you change pivot of a sprite so if you want to add the tip instead it'd be easier

silver fern
#

oh

silver fern
rich adder
#

if you click the sprite and bring it the asset importer window you should see sprite editor.. unless its Unitys sprite then idk how lol

silver fern
#

ah damn

#

yeah its just a diamond shape I drew with the editor

lime wadi
#

how to fix this?

#

trees with black edges, I know that the problem is in the material, but I don't understand a bit

rich adder
odd shale
#

Hi! I’m trying to get all levels from Word Collect APK. I only need the level data in JSON or text format, no graphics or sounds. Could someone extract it?

lime wadi
odd shale
#

mb

silver fern
lime wadi
silver fern
#

can I invoke a unity event that was defined in another script?

#

directly invoking it doesn't seem to work, is there a way to do it?

grand snow
#

yea UnityEvents can

#

event fields cannot

#

an event can only be invoked in the owning class but a UnityEvent is just a class that re creates event functionality so no restriction.

silver fern
#

how do I do that then? do I have to use like a get method to get a reference to the event from the script that defines it?

grand snow
#

call .Invoke() on it

silver fern
#

that's what I'm doing but the event is not getting invoked

grand snow
#

it surely is

#

you must not have subscribed to it or its not the event you think it is

rich adder
grand snow
#

or use a ✨ debugger

silver fern
#

I put a print in the method that is supposed to get called but it does not print, and I have subscribed it correctly in the editor

#

wait do I have to subscribe it in both scripts?

grand snow
#

if you use a debugger and have breakpoints where you Invoke and what you expect to be called then you can actually know whats happening

#

a subscription in the inspector or in code is fine

polar acorn
silver fern
#

I mean, I have it subscribed for the script that creates it but not for the second script that also invokes it

polar acorn
#

You're going to need to be more specific

rich adder
#

trace your code and see where it goes wrong 💫 debugger

polar acorn
#

Like, what is it subscribed to? What is the "other" script in this context?

#

And yes, the debugger will let you step through every line one at a time

silver fern
#

that's not the issue, I wanted to know how to correctly invoke a unity event from a script that does not define that event

grand snow
#

I told you

#

you must have some other problem or be mistaken
use a debugger to debug this properly instead

silver fern
#

no I mean, I am most certainly doing it incorrectly

grand snow
#

Then share some !code if needed

eternal falconBOT
grand snow
#

Is the event on the correct instance that you expect?

#

if the subscription is done in the inspector, is it still valid when you Invoke the event?

silver fern
#

if I just do eventName.Invoke() in another script it tells me eventName does not exist in the current context

grand snow
#

you need to retrieve it from the instance of the class...

rich adder
#

you need a reference to it

grand snow
#

GetComponent<MyCoolClass>().myDumbEvent.Invoke();

rich adder
#

script doesnt magically know about it

grand snow
#

what are you doing 😆

polar acorn
silver fern
grand snow
#

share some code if you need further help because you seem very confused

silver fern
#

so that connection needs to be hardcoded, I was hoping to avoid that somehow

#

ok one sec

grand snow
#

if you want some event that exists "globally" then use a static event:
public static event Action<Debuff> OnDebuffAdded;

#

Here you should avoid UnityEvent because there is no benefit

silver fern
#

maybe my whole approach is just dumb

grand snow
#

I think you forgot about object instances

silver fern
#

in this case, the buff is supposed to change the basic attack to a different one while the buff lasts, so I thought it would be best to call the unity event and have the attack script listen to that and switch attack types when it happens

grand snow
#

something like this could make sense

#

e.g.

public void AddDebuff(Debuff debuff)
{
  debuffs.Add(debuff);
  debuff.OnActivate += OnDebuffActivated;
  debuff.OnDeactivate += OnDebuffDeactivated;
}
#

in this example we subscribe to the events on that specific instance

#

presuming these are something like event Action<Debuff>

silver fern
#
using UnityEngine;
using UnityEngine.Events;

public class CounterShockEffect : EffectObject
{
    public override EffectAlignment EffectAlignment { get; } = EffectAlignment.Buff;
    public override EffectType EffectType { get; } = EffectType.CounterShock;
    public override int EffectAuthorityLevel { get; } = 1;
    public override float EffectDuration { get; set; } = 1;

    public UnityEvent onCounterShockOn;
    public UnityEvent onCounterShockOff;

    public CounterShockEffect(float effectDuration = 1)
    {
        EffectDuration = effectDuration;
    }

    public override void StartEffect(MonoBehaviour mono)
    {
        onCounterShockOn.Invoke();
    }

    public override void StopEffect()
    {
        onCounterShockOff.Invoke();
    }
}
``` this is the debuff class I currently have with the non working invokes
grand snow
#

Ill point out that UnityEvent is a worse replacement for real c# events

#

where do you subscribe to these events though?

silver fern
#

it's subscribed in the skill script, since I was hoping to just call it by name

grand snow
#
CounterShockEffect effect = new();
effect.onCounterShockOn.Invoke();
#

anyway you seem to only care about half of what I say

silver fern
#

that's not true

grand snow
#

its poor design also to invoke some objects event externally

silver fern
#

ok

grand snow
#

(which is why event prevents this wow who knew!)

#

Look just understand that you can subscribe to an event ON some instance, and then invoke that instances OWN event.

silver fern
grand snow
#

If you want to respond to these events on single instances of the effect, then do not use static

#

but then you need to have a reference to the effect to sub and invoke its events

#

if you want to do something when a specific button is clicked, we sub to THAT buttons on click event right?

#

Same exact concept

silver fern
#

yeah I get that

grand snow
#

then do it correctly or realise what you want is different to what you have created soo far

#

but rn i dont actually understand what you want

#

the effect class has the event so why is it hard to access and use?

rare basin
silver fern
grand snow
#

Then your design if flawed

silver fern
#

yes

grand snow
#

If you can't access an instance then wtf is going on

#

Share how you add an effect to the player/thing

rare basin
#

you can use events on non mono behaviour classes just fine

grand snow
#

You can subscribe to an event in code too

#

Also the only way an event is used

silver fern
# grand snow Share how you add an effect to the player/thing

this is in the EffectController

public EffectObject StartEffect(EffectType effectType = EffectType.None, int effectPower = 1, float effectDuration = 0f, int effectFrequency = 0)
    {
        EffectObject effect = null;

        switch (effectType)
        {
            case EffectType.Burn:
                effect = new BurnEffect(damageController, effectPower, effectDuration, effectFrequency);
                break;
            case EffectType.Slow:
                effect = new SlowEffect(characterController2D, effectPower, effectDuration);
                break;
            case EffectType.Quick:
                effect = new QuickEffect(weaponController, effectPower, effectDuration);
                break;
            case EffectType.AspdDown:
                effect = new QuickEffect(weaponController, effectPower, effectDuration);
                break;
            case EffectType.AtkUp:
                effect = new AtkUpEffect(weaponController, effectPower, effectDuration);
                break;
            case EffectType.DefUp:
                effect = new DefUpEffect(damageController, effectPower, effectDuration);
                break;
            case EffectType.ResUp:
                effect = new ResUpEffect(damageController, effectPower, effectDuration);
                break;
        }

        if (effect != null)
        {
            EffectsList.Add(effect);
            effect.StartEffect(this);
            OnEffectReceived.Invoke(effectType);
        }
        return effect;
    }

    public void StopEffect(EffectObject effect)
    {
        EffectType effectType = effect.EffectType;
        effect.StopEffect();
        EffectsList.Remove(effect);
        // Check if this was the last effect of its type
        if (!EffectsList.Exists(entry => entry.EffectType == effect.EffectType))
        {
            OnEffectEnded.Invoke(effectType);
        }
    }```
rare basin
#

holy fuck

#

what is this abomination

#

now imagine you have 50 effect types

#

in your game

polar acorn
silver fern
rare basin
#

how told you to make such structure

polar acorn
rare basin
#

it's a mess

grand snow
silver fern
#

which I am doing by checking a bool in the attack script

polar acorn
silver fern
# polar acorn Okay, so, what is "an attack" and how is it changed? Pick one effect, whatever o...

attack is currently this

    public void AttackOne(Vector3 attackDirection)
    {
        //Visuals
        //Anims
        onLiskarmAttackOne.Invoke();

        GameObject bullet;

        if (ultimateAttackEnabled)
        {
            print("enabled");
            bullet = Instantiate(ultimateAttackPrefab, projectileSpawnerTransform.position, gunHandTransform.rotation);
            UltimateAttackScript ultimateAttackScript = bullet.GetComponent<UltimateAttackScript>();
            ultimateAttackScript.speed = attackSpeed;
            ultimateAttackScript.direction = attackDirection;
            ultimateAttackScript.damage = attackDamage;
            ultimateAttackScript.shieldCollider = shieldCollider;
            ultimateAttackScript.shooterCollider = ownCollider;

        }
        else
        {
            bullet = Instantiate(bulletPrefab, projectileSpawnerTransform.position, gunHandTransform.rotation);
            BulletScript bulletScript = bullet.GetComponent<BulletScript>();
            bulletScript.speed = attackSpeed;
            bulletScript.direction = attackDirection;
            bulletScript.damage = attackDamage;
            bulletScript.shieldCollider = shieldCollider;
            bulletScript.shooterCollider = ownCollider;
        }   
    
    }```
polar acorn
silver fern
#

well the attack spawns the bullet basically

#

and gives it properties

polar acorn
#

Just things like "It changes the prefab that gets spawned" or "it changes some numbers in a script" is what would be sufficient

silver fern
#

it changes the prefab yeah

polar acorn
#

Okay, so, the end result is you want a different prefab if a specific effect is active

silver fern
#

yes

polar acorn
#

Okay, and what is the source of the effects? What causes one to be applied?

silver fern
#

the prefab colliding with a player

polar acorn
#

Prefabs can't collide with anything, they're files

silver fern
#

I mean, the instantiated prefab

#

object

polar acorn
#

So, it's like a power-up in the world, and when the player touches it, it changes their attack?

silver fern
#

it happens on a key press

polar acorn
#

What happens on a key press?

silver fern
#

wait

#

the prefab changing effect happens on a key press

#

when the instantiated object collides with a player it can apply effects too

devout socket
#

I have a spherical player rigidbody that rotates in midair when it jumps via directly setting its angular velocity; however, because it rotates, when it bounces off the ground it moves in the direction of its rotation, and I don't want this to happen
Does anyone know how to achieve this? I tried storing its angular velocity then setting it to 0 in OnCollisionEnter(), then restoring it in OnCollisionExit(), but that didn't seem to work

hexed terrace
#

constation the position on the rb component?

wintry quarry
#

if you want to avoid it, you can set up zero friction physics materials

devout socket
devout socket
#

UPDATE: Setting dynamic friction to 0 and setting "Friction Combine" to "Minimum" achieves an effect close to what I want, but due to the lack of friction the player doesn't roll, instead sliding along the ground
These facts in mind, how can I prevent the player from rolling when landing due to angular momentum without removing its ability to roll?

wintry quarry
round mountain
#

hello, what is this?:

frosty hound
#

!input

eternal falconBOT
#

To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling

• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.

next orchid
#

Hello. I'm making a multiplayer game using FishNet and having issues with OnCollisionEnter not triggering. I'm using a debug statement right at the beginning of it, so it's not getting returned - it's just not triggering at all. My object it's on has a Rigidbody, with 5 colliders as children. It triggers when it hits another object that is a Rigidbody, but not on anything else with a collider. There are no tags or layers being used on anything - it's all set to default. I tried adding a collider to the Parent and that changed nothing. I confirmed no colliders are triggers. I tested with a mesh collider, a sphere collider, and a box collider, and none of those matter - the only thing that matters is if it has a rigidbody on it. I also confirmed the Rigidbody isn't Kinematic.

#

Oh I also tried changing Collision Detection to all the other types and that didn't work either. I also tried putting the OnCollisionEnter script on one of the child objects with a collider and that didn't work either.

compact sundial
#

im trying to add an item to my inventory through a function that I can call whenever I want but I dont know how to convert my item class to a visual element

compact sundial
#

I tried all sorts of ways but im stuck

polar acorn
#

So it looks like arrayOfItems is an array of type Item. You cannot store an Item in a string

compact sundial
#

I was just trying all sorts of stuff

rich adder
#

you don't have a string in Item for name or something ?

polar acorn
#

What value do you want in there

compact sundial
#

uh I think I want it to be a image

rich adder
polar acorn
compact sundial
#

idk I was trying random things

polar acorn
#

So maybe you should think about what you actually want and ask that question

compact sundial
#

this is what it should be

polar acorn
compact sundial
#

this is my item class

polar acorn
compact sundial
#

the icon of the item

#

I am making a drag and drop inventory

polar acorn
#

So you probably want a VisualElement that can display an image

#

I'm not sure if UIElements is part of #🧰┃ui-toolkit or if it's a different thing entirely, but there's probably some sort of image component

rich adder
#

tbh If you're new probably easier to make prefab for ugui and spawn those in
UITK you can do

var img = new Image(){
sprite = mysprite
};```
but there is more to it if you want it interactive
next orchid
rich adder
compact sundial
#

oh I forgot I already have this but I want to add an item through code during runtime

#

for testing purposes

next orchid
rich adder
polar acorn
compact sundial
#

I tried setting CurrentItem.texture2d but CurrentItem wont show up in my function as autofill

#

and its red

polar acorn
#

texture2D isn't a UIElement

polar acorn
#

so that's probably what you want

ivory bobcat
compact sundial
#

it doesnt currently exist in the context

strange jackal
#

my code throws an error I assume when the is no clip? how to I test for a clip

if (animator.GetCurrentAnimatorClipInfo(0)[0].clip)

IndexOutOfRangeException: Index was outside the bounds of the array.

rich adder
rich adder
ivory bobcat
strange jackal
#

the thing is, it works most of the time, it only happens occasionally

#

still can't figure out why

ivory bobcat
#

I'm assuming either a reference wasn't properly setup or is modified during runtime etc

rich adder
#

& is the layer index always 0 ?

strange jackal
#

I check immediately after changing the animation, maybe some lag?

I am controlling animation purely through code

#

so I need the length to know how long to wait before changing again

strange jackal
ivory bobcat
#

Clicking the message once should highlight the animator object. You should verify that it's got a clip

compact sundial
#

im gonna take a break, my brain is fried

sly wasp
#

if you plan on adding different maps, here is my suggestion
When you figure out chunk placing, place your obstacles where you want, then tag them with what specific object they are. Then make a script that places those obstacles into the specific tagged areas, you'll need to add prefab references

strange jackal
random lodge
#

I don't fully understand something. I've tried to make changes to a prefab in the inspector and in the code. The prefab's scripts that change something aren't reflected in the inspector (serialized sections). The code in scripts doesn't seem to update the prefab? Also, if I try to change the rotation of the prefab in the inspector it just appears in the game at its rotation that it had from the start. Totally confused here.

prime nest
#

Hi. Does anyone know if RigidBody2D.linearVelocity is multiplied by delta time (fixed or not) by default?

naive pawn
prime nest
random lodge
#

I can already tell there is going to be an issue with the orientation of this sprite and having to transform it (as a projectile) first according to where an enemy is pointing, but also according to the sprite itself's orientation. It's going to get weird.

#

Sprite "laser projectile" is pointing ---> so "up" is it moving up but pointed in that direction (to the right). Solved it with space.world (and rotating it) because the player is always pointing straight up, but once they aren't... gets weird.

queen adder
#

Man, C# is intimidating

#

I'm afraid to start

eternal needle
rugged beacon
#

if i do kind of

Update(){
   tmp.text = "a";
}

does the canvas know that it doesnt actually change every time and redraw every thing each frame? like how the canvas detect change of an element

random lodge
#

Am I wrong in thinking that a sprite (such as a weapon projectile) might need to be pointed a certain way to make your life easier (before you even use it in the project) or I am just confusing myself.

wintry quarry
#

Generally you want the "forward" direction of the sprite to either be facing right or up.

#

The you can always use transform.right or transform.up in your code

#

Not really a code question though

random lodge
#

Yea but a code issue

#

Been having a hell of a time juggling trying to transform / move the sprite in the right direction because of its orientation

#

Not sure if I am confusing myself

wintry quarry
#

Yeah it's best if all of your sprites use the same convention for forward, either up or right but consistent between all of them

wintry quarry
random lodge
#

Well I had to rotate it and use space.world to get a right-facing sprite to fire "up" in game (shouldn't be using world axis obviously yea). I spent way too long trying to figure out what I should do. Now I feel like if I have AI flying around the scene pointing in any directions am I going to have a massive headache getting the rotation of the "laser" going forward from where they are pointing because the sprite has to be rotated before "firing"? I could be making this more complicate than it is.

barren jay
#

Guys, my game is on Unity 6.2 and im currently trying to learn to use UI Toolkit. I've been searching on google for a while but i cant find the answer so i will ask here. Which one is better for a story game with levels, 1 UI Document for each scene, or 1 UI Document for each game feature? I've been thinking of doing 1 for each game feature, but i'm not sure cuz im afraid of the performance for having multiple UI Document component in a scene.

random lodge
#

Scratch that I think I found one solution

slender nymph
barren jay
#

yeah, my mistake sorry, i've sent the question there too

wintry quarry
#

The transform.Rotate thing in Start is kind of a red flag

random lodge
#

Had to force it

wintry quarry
#

You can set the rotation when you call Instantiate

daring flax
#

does anyone have a tutorial for making a 2d card game multiplayer? I only seem to see stuff that uses a player object in real time, rather than mirroring a board and having turns

random lodge
#

Most of the time rotation seems to change the axis with it. Up becomes to the left because of rotation.

wintry quarry
#

Which means either your sprite is rotated wrongly in the original image or you did something in the prefab with child objects to achieve that

#

Sharing some screenshots of your prefab would help

random lodge
#

Yea it's like this

wintry quarry
#

With tool handle rotation set to "local"

wintry quarry
#

So if you moved it "up" it would appear to be going left

random lodge
#

So I should just transform right all the time and consider it forward?

wintry quarry
#

You need to either edit the sprite or start using right instead of up

random lodge
#

So I did transform.Translate(Vector2.right * projectileMoveSpeed * Time.deltaTime); and Instantiate(blueLaserPrefab, transform.position, Quaternion.Euler(0,0,90)); -- seems to work if that's proper I guess I will see later

random lodge
#

for now I assume that as long as I do that it will always "come out the correct end orientated correctly", until I test it in other ways lol

strange jackal
#

can I make a Spherecast start around the chacter so the character would be in the middle and it would detect things behind?

#

if I made the sphere big enough

wintry quarry
charred spoke
#

I think he wants to start his sphere cast behind his character

strange jackal
charred spoke
#

That could work we do not know what you want to achieve specifically

strange jackal
#

I am an trying to put an agro detection on the enemy so they can detect then agro on player

#

it kinda works with casting, in 4 directions, but that seems inefficient and it leaves blind spots

plush zealot
#

!code

radiant voidBOT
radiant voidBOT
tall heart
#

Does anyone know a video for complete beginners that explains every single code line?

frosty hound
tall heart
#

Thought someone might have something

keen dew
#

nor would it be useful

frosty hound
#

Nothing has changed since a few days ago.

plush zealot
frosty hound
#

You were already redirected to !learn and the resources pinned in #💻┃code-beginner. One would hope you took the initiative and started going through that instead of waiting to hope someone would answer your impossible questions a few days later. 🤷‍♂️

tall heart
frosty hound
#

Then those are the questions you ask help for. Asking for a dictionary for "every line of code" isn't going to be useful.

wintry quarry
#

Why are you using SpriteRenderers at all? Isn't this a UI thing?

#

For UI you use the UnityEngine.UI.Image component

plush zealot
#

🙏 ty

#

ill try that

wintry quarry
#

that's what you should be referencing

#

By default they get one anyway

#

unless you deleted it

plush zealot
#

its not supposed to change the button's image its supposed to change the image the newly made object has

wintry quarry
plush zealot
#

it was this. Instead of the Rawimage in the hirarchy it had the sprite renderer. just added that to try what you suggested

wintry quarry
plush zealot
#

oki imma try it

plush zealot
wintry quarry
#

look at the spawned object at runtime

plush zealot
#

its the same

wintry quarry
#

Have you tried any debugging? Where's your console window?

wintry quarry
#

This code is calling loadPage on the prefab, no?

#

you would need to call it on the actual instance in the scene

#

I also don't even see where you are Instantiating the prefab at all

plush zealot
#

it gets instantiated in 'public void addPageToDeck(); in FightingDeckManager

wintry quarry
plush zealot
#

oh yeah youre right lol i need to call it on the instance of the object

#

ty

wintry quarry
#

Also why is this code so overcomplicated:

        GameObject page2Add = pagePrefab;
        pagesInDeck.Add(e);
        objectsInDeck.Add(page2Add);
        Instantiate(objectsInDeck[pagesInDeck.Count - 1],this.transform.GetChild(0).GetChild(0).GetChild(0)); //child 1 is scroll view obj child 2 is viewport child3 is content
        objectsInDeck[pagesInDeck.Count - 1].transform.position = Vector3.zero;
        page2Add.GetComponent<PagePrefabScript>().loadPage(e);```
#

you have like 4 different ways here of referring to the same object

#

this.transform.GetChild(0).GetChild(0).GetChild(0)
And this is the stuff of nightmares^

wintry quarry
rocky canyon
#

Transform redudantTransform = this.transform.GetComponent<Transform>();

plush zealot
#

because I usually try to get it to work and then clean up the code afterwards

rocky canyon
#

nuttin wrong w/ that

plush zealot
#

imo no point in spending 5 minutes on figuring out how to call it smoother if it doesnt even work in the first place

rocky canyon
#

ya, but on the flip side.. if its overly confusing ur doing urself a disservice trying to figure out what went wrong..

#
Transform content = this.transform.GetChild(0).GetChild(0).GetChild(0);
GameObject page2Add = Instantiate(pagePrefab, content);```
if you insist on the GetChild ladder you can still just clarify it using variables..
it'd make the *rest* of the code more readible
plush zealot
#

objectsInDeck[pagesInDeck.Count - 1].GetComponent<PagePrefabScript>().loadPage(e);
changed it to refer to this instead and it's still not changing it :/

plush zealot
rocky canyon
#

yea u good.. just trying to be helpful.. with tidbits

plush zealot
#

am I referencing the right thing? is Image.Sprite the sourceimage?

rocky canyon
#

yourImage.sprite but yea

#

did you change it to grab the Instantiated clone rather than the prefab?

#

use .name to log the objects and make sure they are what u believe they are.. and so on

strange jackal
plush zealot
#

im referencing the objct in the List

plush zealot
#

the switch isn't working properly .-. its not a technical issue

plush zealot
#

I'm failing to understand why it's Debugging "Null" when the element is hard coded into the different Pages

rocky canyon
#

you're missing a reference

#

line 48 of Ebooks.cs

plush zealot
#

thats not an issue those are light and dark

#

dont have them implemented yet

rocky canyon
#

well.. ur working on that script it is an issue..

#

null reference stop the code from running

#

soo... if u get that error anything left in that script isnt gonna work

plush zealot
#

in the instance yes

#

but I have that script on different objects

#

the other elements are implemented

#

and still don't return the right element

rocky canyon
#

well ur debug of Null is ur major hint..

#

if its null.. u need to figure out why its null..

#

so.. back-track that variable

#

debug.. it more

#

find out when it becomes null.. or rather... why its null..
instead of what u expect it to be

plush zealot
#

hm oki

grand snow
#

why not try using the debugger in rider?

keen dew
#

And if you want help with it you'll have to show what you're trying to log. The screenshot cuts out the relevant part

plush zealot
#

ill check some stuff and come back if i cnat figure it out

#

ty

#

I implemented the elementpage incorrectly. Wasn't inherited properly so it instead created a new one while getElement was checking the inherited variable "element"

strange jackal
#

agro is working well...

next orchid
random lodge
#

How can you get the quaternion z position rotation and store that in a variable?

#

Sorry rotation

rich adder
random lodge
#

As an example

rich adder
random lodge
#

Yea I'm just saying I need what is here (0,0,here) and store it in thisfloat.

#

So I can take that and add 90 to it etc

wintry quarry
random lodge
#

There, that seems to work

#

Sorry for confusion in terms, my brain was working like the sound of a dial-up modem off the hook.

west sonnet
#

Is it possible to add a reference to a prefab's child object in a Sciptable Object?

grand snow
#

No you can only reference the asset

west sonnet
#

Is it possible to detect when a raycast has hit an object from the perspective of the object? Like, I know you could do an OnCollisionEnter for phyics collisions, is there any equivalent for that for raycasts?

keen dew
#

No. Whatever does the raycasting must message the object

grand snow
#

yea why cant you just call a function on the hit object...

#

hint: very easy to do

strange jackal
#

I am trying to get a direction to go an object using moveDirection = (agroTransform.position - transform.position) however, the movement speed is affected the further away the two are... I have tried dividing by distance, but is there a way to simply get the direction to an object so I can multiply it by my speed setting?

grand snow
#

normalise the directional vector

#

which makes its length 1

open marten
#

My code isnt working i don't know whats wrong with it

#

I Just want my flappy bird to flap but the space key isnt doing anything

slender nymph
#

!code

radiant voidBOT
open marten
median hatch
#
void Update()
    {
        if (isVitaminShot && targetEnemy.hasFoundEnemy)
        {
            Vector3 directionToEnemy = targetEnemy.enemy.transform.position - transform.position;
            directionToEnemy.y = 0;
            directionToEnemy.Normalize();  // Ensure the direction is a unit vector

            // Move the bullet forward in the new direction
            transform.rotation = Quaternion.LookRotation(directionToEnemy);
            transform.Translate(Vector3.forward * (bulletSpeed / 10f) * Time.deltaTime);

            targetEnemy.hasFoundEnemy = false;
        }

        transform.Translate(Vector3.forward * bulletSpeed * Time.deltaTime);
    }

does anyone know why my bullet is teleporting when targetEnemy.hasFoundEnemy is true?

#

i want it to smoothly rotate towards the enemy for a frame

slender nymph
#

why do you translate it a second time that frame?

median hatch
#

sorry this is actually the current version

void Update()
    {
        if (isVitaminShot && targetEnemy.hasFoundEnemy)
        {
            Vector3 directionToEnemy = targetEnemy.enemy.transform.position - transform.position;
            directionToEnemy.y = 0;
            directionToEnemy.Normalize();  // Ensure the direction is a unit vector

            // Move the bullet forward in the new direction
            transform.rotation = Quaternion.LookRotation(directionToEnemy);
            bulletSpeed /= 10;

            targetEnemy.hasFoundEnemy = false;
        }

        transform.Translate(Vector3.forward * bulletSpeed * Time.deltaTime);
    }
keen dew
#

"Smoothly rotate for a frame" is a contradiction. One frame can have one change in rotation. If you want to do it smoothly you have to do it over multiple frames

median hatch
#

this is how it looks like

#

@keen dew

languid pagoda
#

I like your lighting and the overall aesthetic!

median hatch
#

coming to steam soon

languid pagoda
devout socket
# devout socket I have a spherical player rigidbody that rotates in midair when it jumps via dir...

I would like to ask this question I asked yesterday again, as it continues to stump me
Since making that post, I have tried:

  • Using rigidbody constraints to prevent the undesired movement (could not find a good way to store/reapply both angular momentum and direction after the constraints were removed)
  • Changing the player's physics material to remove all friction to prevent the undesired movement (worked, but ruined various other aspects of the player's movement)
    Things I have considered but haven't tried yet, mainly because they sound overly-complicated for the problem I'm trying to solve:
  • Using contact modification to remove friction considerations from the player when it lands (I cannot find any form of documentation or tutorials for the contact modification API)
  • Making a "landing only" physics material that I swap out the regular one for one frame every time the player lands (sounds promising, but also sounds like it will create a lot of problems)
    Could I ask for advice on what to do here?
ivory bobcat
languid pagoda
#

Also have you tried rotating via setting transform.rotation rather than setting the angular velocity?

devout socket
fervent parcel
#

is there a way for me and my friend to work on our game in real time?

devout socket
west sonnet
#

Is it generally advised to not used Gameobject.find ?

grand snow
west sonnet
#

Is it okay to use in Awake or Start?

#

Since it'll only be run once

bitter condor
grand snow
median hatch
grand snow
#

Find("Player (Clone)") 🙂

muted geyser
#

also

#

"PipiMove"?

languid pagoda
devout socket
# languid pagoda Can't you just reference it and change the value?

I think I just fixed it
I remove all friction from the player in OnCollisionExit() and restore it in OnCollisionStay()
Just after that in OnCollisionStay(), I check if the player isn't moving horizontally but does have angular velocity, and if they are, I remove all their angular velocity
Thank you for your help! :)

polar acorn
#

Does the new bot not work with commands in the middle of lines any more?

#

!code

radiant voidBOT
polar acorn
#

There it is

languid pagoda
#

Any idea how I can simulate tire heat?

#

like is there any decent equations for the heat generated by friction?

timber tide
#

one heat to one friction

languid pagoda
polar acorn
#

Isn't friction like, definitionally energy lost due to heat

languid pagoda
polar acorn
#

Yeah but since force requires energy and energy can't be created, the counter force must come from the heat energy

#

The speed loss comes from some amount of kinetic energy converting into heat

#

!code

radiant voidBOT
languid pagoda
timber tide
#

Try again

#

Oh, it's way too big. Yeah, throw it in a paste site

#

So what's the problem

slender nymph
polar acorn
#

!code

radiant voidBOT
keen dew
#

AI code 🤢

#

You have the debug log there, does it ever show that isGrounded is false?

#

Then the ground check is wrong

#

You'll have to do more debugging

#

What is the groundCheck object set to, what is the value of groundCheckDistance, what is the groundLayer set to

#

What does the debug ray show

#

Ok first of all, the console isn't supposed to show anything. Read the comment above the DrawRay call

#

groundCheck is supposed to be set to the object that detects the ground, not the ground itself

open apex
#

Hello there, have been learning programming with c# on my own, trying to stay away from chatgpt and discord as much as possible but I have hit one of those no go topics. I am looking into LINQ and all I can find is basic tutorials nothing in depth. I can ask chatgpt but I don't want to as it doesn't help with critical thinking and push us to look for answers.

So here is my question:
I have a list with a class I have created. I will be getting string input from the user and I want to look throught each x string in the array and find the best matches possible from the given string (so not exact match, best matches). Example: Array {"MyPotatos","TheApples","RottenPotatos", "I need help with potatos"} Input from user = "Potatos". From array look through strings and find best matches to user input. Result: "MyPotatos","RottenPotatos", "I need help with potatos"
please someone help people
I am becoming a bit desparate

keen dew
#

Stop copy-pasting code from AI without even reading it and follow a proper course

polar acorn
strange jackal
#

I'm getting the following warning, even on a new, empty scene
CommandBuffer: built-in render texture type 3 not found while executing (SetRenderTarget depth buffer) UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

eager spindle
crisp lodge
inner badger
#

Hello, new to the group and just started learning C# and Unity. Are there any recommended free courses/YT channels to learn the basics? TIA!

slender quiver
#

anyone have any idea why my inspector is suddenly displaying stuff weird?

languid pagoda
#

is there a way to make it so [SerializeField] only happens if a variable in the script is a certain value? I want different values to display in the inspector depending on what type of object it is. ie TireType.Pacejka or TireType.Brush

slender quiver
#

that stuff happens at runtime, whereas the serialization happens beforehand, and can be editted outside of runtime

naive pawn
#

being serialized and being shown in the inspector are 2 different things that happen to mostly overlap

languid pagoda
languid pagoda
#

how do I edit what is shown in the inspector?

naive pawn
#

with a custom property drawer

languid pagoda
#

Thank you now I can do some looking on the docs!

slender quiver
#

forgive me then im a moron

#

and i figured my thing out, commenting the headers out calmed it down

languid pagoda
#

oh wow

#

that second link has some shit i can just copy paste over pretty much

#

dope

#

Thank you @naive pawn you in here putting in work all the time.

slender quiver
#

i am not understanding why i cannot assign these objects in the prefab to the my SO ShipData's mount system

naive pawn
#

!code

radiant voidBOT
slender quiver
#

ngl chris that gets to be a real pita 😛

#

i figured that was a small enough chunk an image would be fine, guess not

naive pawn
#

it makes my job a lot easier

#

representing text as text is a lot better than representing text as an image

slender quiver
#

aye but you !code when ppl use triple backticks too

naive pawn
#

(for the small chunks you're trying to show you could also use the inline code part, but this works too)

naive pawn
slender quiver
#

alright

#

i got you

naive pawn
#

kinda looks like the mount location field is grayed out?

#

(why make it an Object though)

#

GameObjects and Transforms are 1:1

slender quiver
#

see before i got type mismatch

#

dropping the GO onto the Transform field

naive pawn
#

huh come to think of it, that could be why - it'd be ambiguous what you're trying to assign

slender quiver
#

thats why i tried to drill down into the setter and make it possible to use a GO or a Transform explicitly

naive pawn
slender quiver
#

and it forced me into using Object instead of GO

#

so idk

naive pawn
#

what object are you trying to assign onto?

#

ah wait, a ShipData SO, right?

#

im not sure you can reference children of a prefab like that..

#

it's kinda like the scene object into asset context thing

slender quiver
#

hmm, how to best store the information then

naive pawn
#

would it be possible to just store it all as a component on the prefab?

slender quiver
#

yeah so i should just make the ShipData an MB instead of an SO, basically?

naive pawn
#

yeah

#

if that makes sense for the data you need to store - i don't have full context of what you have the SO doing

slender quiver
#

well its supposed to be data on the ship in question. name, nation, type, level requirement, what weapon mounts it has for primary/secondary guns, where the transform to instantiate whatever guns get equipped goes, the rotational limits for each turret location, etc

naive pawn
#

yeah that probably could be on the prefab

slender quiver
#

off topic but im pretty proud of how my blendering has come together so far too 😛

#

alr thx for the help, my roommate is nagging me to go to the gas station for him, ill ponder as i go and try to convert it over and see how much better it goes afterwards

languid pagoda
#

anyone know a decent forumula to calculate tire temp? i seen the ones on google just curious if anyone has used one they know works

slender quiver
#

@languid pagoda
no idea but youre making me curious about the nature ofyour project lol - racing?

languid pagoda
#

yes

#

well really just vehicle physics

#

i have no intention of actually making a game

slender quiver
#

ah neat - i assume youre aiming to drill down pretty deep into simulation then??

languid pagoda
#

yes for the most part

#

have a custom multi model wheel collider

#

can use pacejka or brush tire model using raycasts for suspension

slender quiver
#

that sounds pretty awesome, but i know nothing about tire models

hushed hinge
#

https://paste.mod.gg/tkekcmnhsknf/0 how can i make sure that the player doesn't get bounced up whenever the paltform moves down or up? (one reminder, the reason why i am not using parenting because that would make that the player unable to follow the platform despite being a child object to it because the platform is kinematic and the player id dynamic, even whe full kinematic contacts, it wont work)

frosty hound
#

How are you actually applying the force onto the character controller when it is on the platform?

hushed hinge
frosty hound
#

Well, ignoring the fact that alone is a red flag, then of course it will make your player "float" at the top because the frame before the platform goes down it has moved your character up one frame by the movement delta. And because your character's falling has acceleration, it's "disconnecting" from the platform.

#

Anyway, the solution is likely in needing to flip the authority on what has control over your character. The platform shouldn't be "moving" the rider at all, it should only care about it's current velocity. The rider is the one that should be detecting that it is on a moving platfom and then applying the velocity of that platform to it's combined velocity/input from the player.

hushed hinge
# frosty hound Anyway, the solution is likely in needing to flip the authority on what has cont...

I get what you mean about flipping the authority, I’ve tried the ‘platform just provides velocity, and the rider applies it’ approach a bunch of times. The problem I kept hitting is that because my platform is kinematic and my player is dynamic, simply parenting the player to the platform doesn’t work, the player won’t inherit the movement, even with useFullKinematicContacts enabled. That’s why I ended up trying to directly add the delta to the rider’s position

frosty hound
#

Switching the authority has nothing to do with parenting the player. That should never be a thing.

hushed hinge
#

Then I don't know what to change

#

or what authority you mean

frosty hound
#

Right now your platform is actively overriding the position of the thing that is on it, that authority.

#

Your platform should be a dumb object that has no idea anything is on it. It simply goes about moving along it's assigned route.

#

The actual smart object, your character, is the one that determines it is on a moving platform and takes the velocity of that platform into account when determine it's current frame velocity by factoring it into whatever other velocities are being applied - such as your input.

#

The platform can have it a property Velocity that it continually updates as it moves about, which your character can use.

hushed hinge
#

so, make a different script something like PlatformRider for the PLayer?

slender quiver
#

Maybe generalize it more. A script to detect what the player is in contact with, reference its velocity for its own velocity updates

#

all surfaces, even mobs maybe, expose their velocity. if player stands on something, it will interpret its velocity as a product of input + surface its on. most surfaces wont move and have velocity of zero

hushed hinge
#

or player have another script that checks if it's on the platform?

frosty hound
#

However you want to do it 🤷‍♂️

#

The theory is there, you can execute it

hushed hinge
#

yet i am afraid that the player woudl still bounce up anyways

frosty hound
#

Then that would be an issue with your implementation

hushed hinge
#

well i am thinking on changing up the platform script first

#

so is there a script i can find and maybe a tutorial that have like a separate script that detects when the player is on the platform?

frosty hound
#

If there is, I'm not going to be the one to look and find it for you 🤷‍♂️

hushed hinge
#

well already looking for it

frosty hound
#

This video implements it the same way you have, and suffers from the same issue. Their bandaid fix is to increase the gravity scale so that you don't notice the disconnecting because the player essentially speed falls back into the platform.

hushed hinge
#

oh

#

but still work in a way?

frosty hound
#

Sure, until you find another edge case where it conflicts and are back here asking how to work around that one.

hushed hinge
#

ok

hushed hinge
#

well the first steps seems to be going alright

hushed hinge
#

after finding a tutorial and adjusting for the loop and ping pong

languid pagoda
languid pagoda
#

huh wasn't even an issue with my code i deleted the object and recreated it and now its fine ?

#

lol

slender quiver
#

this is for help writing code in unity

west sonnet
#

This Awake() method is called whenever a new weapon is picked up. It is specific to each weapon. Is this okay?

slender quiver
#

I dont see why not

keen dew
#

It's "ok" in the sense that it probably works but it's not really following any best practices. It looks like those scripts should be singletons or there should be one (or more) top level managers for handling those things

west sonnet
slender quiver
#

exactly, attached to a gameobject placed somewhere in the scene

keen dew
#

Either a singleton that you can use to access those components anywhere (Manager.CamRecoil for example) without having each individual component find the components separately, or a manager that creates the weapons and assigns the references to the weapons at that point

slender quiver
#

for instance you can see my GameManager object that has a few management components attached to it in the inspector

west sonnet
#

What's the benefit of using a GameManager like that? The components I'm referencing are being used in that same script, so would using a GameManager make it more complicated?

#

Because I then have to create more references

cosmic grove
#

hey guys. i just tried the 3D Beginner Game: Roll-a-Ball tutorial on unity website to get a hang of the engine. In the player input, this warning is shown. And i cant move my player. Do i need to fix this warning first?

#

this is the script so far

keen dew
molten dock
#

Have the weapons already attached to the player and connect through inspector

#

Disable what is not currently picked up

west sonnet
molten dock
#

Yes this is my solution for that

keen dew
west sonnet
#

Like the CamRecoilScript

keen dew
#

You make serialized fields and drag the references in the inspector

west sonnet
#

Serialized fields in the weapons script?

keen dew
#

No in the manager

west sonnet
#

Oooh, so I don't need to do the FindObjectWithTag ?

keen dew
#

Then in the weapon script GlobalReferences.Instance.Camrecoil

#

Yes the entire point is to avoid using the Find* methods

west sonnet
#

Right, that makes sense. Thank you

grand snow
#

I go the route of manual initialisation so I can provide dependencies then as args and avoid both find and static fields

#

dependency injection frameworks exist for unity that can do this for you

worn bay
#

Hi, I'm a bit new to using the profiler; what does these mean (and why is EditorLoop taking the most Time ms)? I'm on deep profiling mode and these seems to be Unity builtins or some sort?

#

additionally the game is stuck at ~60fps despite the target fps being set to 90 (tried disabling vsync whenever possible)

grand snow
#

In editor the editor executes things each frame which is why its included in the profiler
PlayerLoop is for the game

#

14ms to render canvases is pretty high

worn bay
#

All I'm seeing is extension/builtin calls

grand snow
#

How much stuff is in your canvas? Are you making use of sub canvases?

#

We can see canvas render has the 14ms time

worn bay
#

the canvas in said scene looks like this

#

(On 2022.3 btw)

grand snow
#

When a single object in a canvas is made dirty the whole canvas has to be rebuilt

#

You can use canvas components within a canvas (add them to child objects) to optimise what gets rebuilt

worn bay
#

(the canvas child is just Transform and RectTransform iirc)

grand snow
#

its easy
If you have a fuck ton of things in 1 canvas its going to increase its redraw cost greatly

#

e.g. add canvas component to "Game View"

#

may also require a graphic raycaster component if input stops working

#

Hopefully you know what things in your canvas get changed a lot so you can judge best where to have a "sub canvas"

#

The point is to prevent things that dont change very often or at all from being re built

worn bay
#

well I'd say having to redraw the entire HUD and other stuff just because it triggered a hit particle would make sense that it'd be costly

grand snow
#

Does this make sense though?

worn bay
#

do I just do it like this?

grand snow
#

yep and now its children will be rebuilt by this canvas and its seperated from any parent canvas

#

Don't slap them everywhere but where it makes sense

worn bay
#

do I need to update any scripts for that to actually happen or the editor will just take care of it?

grand snow
#

nope nothing like that is needed

worn bay
#

alr thanks

worn bay
#

welp at least it's throttled by smth else now kekwait

#

the consequence of not admitting defeat to DOTween

worn bay
# grand snow keep it up 🧠

Well I'm having issue with lookups now

// Navigate forward
while (true) 
{
    // Get the next timestamp in the list
    Timestamp timestamp = null;
    
    foreach (Timestamp storyboardTimestamp in Storyboard.Timestamps)
    {
        if (timestampType.ID == storyboardTimestamp.ID)
        {
            timestamp = storyboardTimestamp;
            break;
        }
    }

this is a bad search method for something done on high volume of calls, but it's too simple to be able to think of anything better UnityChanLoom

keen dew
#

At a surface level, use a dictionary instead of a list. "Get the next timestamp" suggests maybe they could be ordered so that it could just pick the next index

worn bay
#

ID is an enum, if that helps

grand snow
#

Cool that works in a dictionary still

keen dew
#

or if the data is paired then make them structs so you don't need to search for the pair every time

worn bay
#

Tried it, it breaks (oor it's just I'm too incompetent to mess with this >.>)

keen dew
#

it's the latter I'm afraid

worn bay
#

I don't have a good grasp on how dictionary lookups would work

#
  • last time I have dictionaries in other places, it has a pretty high self ms in profiler for some reason
grand snow
#

It should be better when you have many things in a collection

worn bay
#

do I keep the timestamp = null part

keen dew
#

If there's more than 1 or 2 items in the collection it's pretty much guaranteed to be faster than iterating through a list

#

unless there's a custom hashing function and it's royally messed up

worn bay
#

Well iirc Storyboard.Timestamps is sorted chronologically (since it's a rhythm game)

#

so grouping it by IDs sometimes makes me think it's not the best idea

keen dew
worn bay
#

when I implement it, it either; 1. Executes by type instead of time (i.e Rotates THEN transforms, instead of doing both in parallel) or 2. It stops moving altogether

slender quiver
#

I shouldve put that in a pastecode sorry

grand snow
#

Values and where wtf

keen dew
#

can't know what it is without seeing the code

keen dew
#

So which is the problem with this code?

lunar coral
#

hi,I don't really know how to ask my question, but I've been trying to make AI bots that are animated and shoot at the player(military bots) for 7 days and I can't achieve what I want, I would want to know if there are tutorials that would help me or if there are other solutions, it's my first time trying to do this and it's always nice to have some documentation to start with

worn bay
keen dew
worn bay
#

(I reverted them)

#

I'll probably go check somewhere in my git tree if I kept it somewhere

#
if (!CurrentValues.TryGetValue(timestampType.ID, out float value))
{
    continue;
}

if (!Storyboard.TimestampsByType.TryGetValue(timestampType, out var timestampList) || timestampList.Count == 0)
{
    continue;
}

while (timestampList.Count > 0) 
{
    var timestamp = timestampList[0];
    

something like this

strange jackal
#

I can't figure out what to fix here
NullReferenceException: Object reference not set to an instance of an object UnityEditor.Graphs.Edge.WakeUp () (at <d7deb46552984aa294977920c8085e3d>:0) UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List1[T] inEdges, System.Collections.Generic.List1[T] ok, System.Collections.Generic.List1[T] error, System.Boolean inEdgesUsedToBeValid) (at <d7deb46552984aa294977920c8085e3d>:0)
UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at <d7deb46552984aa294977920c8085e3d>:0)
UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at <d7deb46552984aa294977920c8085e3d>:0)
UnityEditor.Graphs.Graph.WakeUp () (at <d7deb46552984aa294977920c8085e3d>:0)
UnityEditor.Graphs.Graph.OnEnable () (at <d7deb46552984aa294977920c8085e3d>:0)`

worn bay
strange jackal
#

I don't even know what script is causing it

#

when I double click it doesn't take me to a script

cosmic dagger
strange jackal
#

I hate seeing errors 🙁

mint swift
#

your scripts are running all fine?

strange jackal
#

ya, game still runs

mint swift
#

yeah ignore it then

silver fern
#

does anyone here know a lot about using scriptable objects?

keen dew
#

If you have a question just ask it and if someone knows they'll answer

silver fern
#

I currently have a badly designed buff debuff system that I'm supposed to replace by a system using scriptable objects but I can't figure out how to do that in a way that actually improves my situation

limpid cloak
#

i wanted to create an if statement that checks the amount of instances of a specific gameobject currently present in the scene and if they are higher than a set amount, it would disable the player's ability to spawn more, but apparently you can't just use >/</= signs for gameobjects

keen dew
#

Well you can use them for the count of gameobjects but that's a bad way to do it

#

Make a variable that tracks how many have been spawned

west sonnet
limpid cloak
#

probably because it's more laborious to make it account for the gameobject deletion

#

like it can count but you also need to make a separate instruction to decrease the counter when the gameobject is deleted?

limpid cloak
#

i could make a list i guess

keen dew
# west sonnet Why is that a bad way to do it?

Basically the same reason why using Find is bad, because information about the state of the game should not be derived from the scene but there should be an authoritative source about the state

#

Counting the gameobjects is fine but arguably better would be to have something else track them. Store them in a list and remove them from there the same time they're destroyed

slender quiver
#

ideally being the thing that issues the command to create whatever it may be that youre tracking, and such

silver fern
#

alternatively, does someone know a good way to invoke a unity event in a different script?

slender quiver
#

single source of authority and all that

keen dew
#

Also if you're just counting the instances that are in the scene it implies that there's nothing controlling what can spawn the instances and they can just be created willy-nilly. Having just one thing be responsible for spawning and destroying the objects pays in the long run

limpid cloak
keen dew
#

I was thinking you'd store the instances in the list because it can be useful for managing them also in other ways

#

but if you just want to keep count then make an int and ++ it

limpid cloak
#

i mean i could do that i guess.. i'm not familiar with managing objects and instances scripting wise. unity tutorial makes them feel almost like classes

keen dew
#

And again it's fine to just count the objects if you don't want to completely redesign the code structure. Just remember to check the count with >= etc instead of the collection itself

cosmic dagger
cosmic dagger
limpid cloak
#

oh ok you mean like that

#

i'll see what i can come up with

cosmic dagger
limpid cloak
#

ok, i made a private List<GameObject> dogCounter = new(); and added a dogCounter.Add(gameObject); in the if statement. now, this is all on a PlayerController monobehaviour, but what removes the game object in question is inside another monobehaviour called DestroyOutOfBounds. can monobehaviours share commands or communicate with eachother? if not i will just add a timer that makes the list delete one item after the amount of time it takes for the object to go OOB and get deleted

balmy vortex
#

Does anyone know how to actually sync up my health bars value to the value in my code?
rn it grabs the value from the slider but altering it in the code doesn't actually do anything and changing the healthSlider to be static kinda just breaks everything

cosmic quail
#

so if player health is 50 then slider should be 0.5

cosmic dagger
balmy vortex
#

ty king

cosmic dagger
cosmic quail
# balmy vortex ty king

btw next time ask a question in one channel only 😉
cuz crossposting is against the rules

silver fern
#

I'm not using static anywhere, my method is public override void StartEffect(MonoBehaviour mono) { Debug.Log("invoke event"); Debug.Log(mono); mono.FindAnyObjectByType<LiskarmSkillScript>().onCounterShockOn.Invoke(); }

#

and I get that error

keen dew
#

In your code the type name is MonoBehaviour and instance reference is mono

silver fern
#

ohh

#

thanks

keen dew
#

so "cannot be accessed with mono; qualify it with MonoBehaviour instead"

silver fern
#

is there any way to limit the find to only look in components attached to the character the find was called from?

#

I'm in EffectController and want to find a component in PlayerControllers, but when I have two of the same character, it finds the component in the other character instead of this one

cosmic dagger
cosmic dagger
#

Or GetComponentsInChildren to search for a component . . .

limpid cloak
keen dew
limpid cloak
#

now i just need to understand how to block the input from instancing while the list is at 1 or higher

cosmic dagger
# silver fern it's not a child

You should properly provide all the information instead of drip-feeding. It's hard to tell what you need with so little information . . .

silver fern
#

I doubt you want to know all of it

#

but I can show you all of it if you want

#

I did post the screenshot of the hierarchy showing its a sibling

#

actually I can probably do something like parent.GetComponentInChildren

#

hmm it doesnt know parent

keen dew
#

transform.parent

silver fern
#

thanks that did it

cosmic dagger
silver fern
#

wut

limpid cloak
#

still, learning is important

#

unrelated to unity, but how do you disable in VS that thing that makes you replace a character instead of inserting a new character? like when it does that grey overlay over a character

silver fern
#

push insert key on your keyboard

limpid cloak
#

lifesaver

silver fern
#

lol

digital jacinth
#

iam beginner at coding, i know how to use functions, if statements, bools, gameObjects, Vector3 and Vector2, but i dont know what to learn now, what should i learn?

timber tide
#

learn to make a game

keen dew
#

What do you want to code?

silver fern
#

If I rotate a transform, does the collider not rotate with it?

worn bay
junior ivy
#

why should I use Graphics.RenderMeshInstanced when Graphics.RenderMeshIndirect gives me much more flexibility?

grand snow
worn bay
#

I see

digital jacinth
#

can i check what other things that i can learn?

#

like if statements

grand snow
# worn bay I see

If you say had a canvas on your parent for an inventory UI and no more then it would be good.

digital jacinth
#

i dont want to learn multiple things at once

worn bay
cosmic quail
digital jacinth
#

in the site that you sent?

#

or in youtube?

cosmic quail
digital jacinth
#

oh oke

#

thanks

grand snow
#

If needed perhaps another canvas for say a grid of items could help but depends

spring oak
#

so uh why can't I select my method from here

silver fern
rich adder
spring oak
#

oh

#

i forgot

#

lol

#

thx

silver fern
#

is there a better way to check for collisions with a polygon collider than Physics2D.OverlapCollider?

slow blaze
#

why is there a conflict here? I'm merging a branch into main, said branch doesn't have another definition for SampleScene.Unity

slow blaze
#

doesn't say anything really

#

I wouldn't be here if it did

naive pawn
#

the commandline or your ide's integration don't give you any more info whatsoever?

grand snow
polar acorn
grand snow
#

if they merged some branch into theirs then "local" doesnt mean anything

#

if you had working copy changes that conflicted then a merge would just fail

broken vine
#

hello! im trying to get into 3d developing with no experience with coding or developing as ive been inspired by TVGS who made the game schedule 1. Within unity what coding language do they use as im not experienced with coding at all and how would i be able to learn it?

broken vine
#

!learn

radiant voidBOT
strange jackal
#

I can't get my arrow to fly, it just stays
`
newArrow = Instantiate(arrow);
newArrow.transform.SetPositionAndRotation(arrow.transform.position, arrow.transform.rotation);
newArrow.SetActive(true);

private void FixedUpdate()
{
if (newArrow != null)
{
newArrow.GetComponent<Rigidbody>().AddForce(arrow.transform.forward * arrowSpeed, ForceMode.Impulse);
}
}
`

polar acorn
strange jackal
#

void FixedUpdate() { transform.GetComponent<Rigidbody>().AddForce(transform.forward * 20, ForceMode.Impulse); }

polar acorn
#

Possible, no idea what Network Rigidbody is doing

languid pagoda
#
if (tireTemperature > ambientTemperature)
    {
        tireTemperature -= cooling * deltaTime;
        if (tireTemperature < ambientTemperature)
            tireTemperature = ambientTemperature;
    }

    // Heat from slip & load only when on ground
    if (suspension.IsWheelOnGround)
    {
        // Slip magnitude: longitudinal slipRatio + lateral slipAngle (in radians)
        float slipMag = Mathf.Abs(slipRatio) + Mathf.Abs(slipAngle) * Mathf.Deg2Rad;
        slipMag = Mathf.Clamp(slipMag, 0f, 3f); // cap extremes to keep it stable

        float loadN = suspension.fZ.magnitude;               // normal force (N)
        float mu    = Mathf.Max(0f, tireData.frictionCoefficient); // friction scale

        // Simple heating: proportional to mu * load * slip
        float heatGain = heatingCoefficient * mu * loadN * slipMag;

        if (heatGain > 0f)
            tireTemperature += heatGain * deltaTime;
    }

any idea how I can improve this? seems like no matter how much I play around with the coefficients i cant get the values consistent.

#

either is heats up way too fast or way to slow

strange jackal
silver fern
#

did you write the method correctly?

languid pagoda
rocky canyon
#

this makes no sense..

strange jackal
#

no

rocky canyon
#

if tireTemp > ambTemp.. then the nested if statement would never be true

#

maybe u didnt meant to nest it there

languid pagoda
rocky canyon
#

ya, but it runs in a single frame..

#

the NEXT frame when it loops back over..

#

think about it in terms of values.. and step thru it..

#

if u step thru it.. its never gonna run

#

maybe 1 single time

#

ahh

#

ur using it like a clamp

languid pagoda
#

yes

rocky canyon
#

okay carry on then, mb

#

havent seen a clamp like that in a while lol

languid pagoda
#

no problem lol i was so confused

rocky canyon
#

me too 🫠

languid pagoda
#

im about to ditch it and try again anyways

rocky canyon
#

i would.. if its taking consider amount of time to debug

#

it might be more cost efficient to redo it

strange jackal
#

I stripped it down, added a sphere, added a rigid body, added the script
void FixedUpdate() { Debug.Log("is fixed working ?" + Time.realtimeSinceStartup); transform.GetComponent<Rigidbody>().AddForce(transform.forward * 20, ForceMode.Impulse); }
and it works, so must be a problem with my arrow object

languid pagoda
rocky canyon
#

ohh... and i also agree w/ u bout the car stufff
a cars sillhouette almost likely will be copyrighted/ legal issues

strange jackal
#

should I use FixedUpdate? or just Update

strange jackal
rocky canyon
#
 void FixedUpdate()
    {
        Debug.Log("is fixed working ?" + Time.realtimeSinceStartup);
        transform.GetComponent<Rigidbody>().AddForce(transform.forward * 20, ForceMode.Impulse);
    }```
languid pagoda
#
```csharp
   /// code here.
rocky canyon
#

^ this..

silver fern
#

!code

radiant voidBOT
rocky canyon
#

single ticks are for single lines

half lantern
#

hi, when you make a unity game, how can you make it for pc and mobile?

silver fern
#

for some reason the CS has to be in capital letters for me or it doesnt work

rocky canyon
silver fern
#

oh yeah nvm

half lantern
silver fern
#

I'm just not smart

rocky canyon
silver fern
rocky canyon
strange jackal
rocky canyon
#

are u wanting to make the same code work in both builds?

#

w/o modding the code?

half lantern
#

yes

rocky canyon
#

yea i'd have to think about that.. im not all that well versed in the new input system tho

half lantern
#

without changing the code, just a game thats identical but obviously different ways of controlling character

#

ok ill research it

rocky canyon
#

i can help search around.. but thats all i can do

silver fern
#

it's very easy with the new input system

half lantern
#

can devs just make builds for any device?

rocky canyon
half lantern
#

i have some expereience with new input system

rocky canyon
#

im pretty sure thats 1 of the perks of the input system

strange jackal
#

just confirming, should I use FixedUpdate()? or just Update()

rocky canyon
#

1 actionMap = multiple platforms

silver fern
languid pagoda
half lantern
languid pagoda
rocky canyon
#

if done correctly yes..

#

i believ

silver fern
#

depends on what exactly you're doing probably

strange jackal
half lantern
languid pagoda
# half lantern using the same code?

yes my car controller works with a keyboard a controller and a steering wheel + pedals its the same code for all I just added more bindings in the action map

silver fern
#

if you're targeting device specific features that wont work on other devices you'll have to adapt

half lantern
#

is there features for the ui where you can just scale it depending on screen size

languid pagoda
rocky canyon
half lantern
#

where do you guys learn about ui

#

isn't there a ui ebook. did you guys use that

languid pagoda
silver fern
#

I just look for tutorials online

strange jackal
rocky canyon
#

yo russell.. ur values are probably way too high

half lantern
#

ok thank you so much

rocky canyon
#

u need really small decimal values

#

like coolingrate would be like .2f

heatingCoefficient should be even smaller like .0002f

languid pagoda
languid pagoda
#

i was using like 0.5

rocky canyon
#

Treat coolingRate and heatingCoefficient as tuning knobs. Start super low, then bump up until it “feels” right

#

and i mean super low lol

#

since ur running possible +60fps

languid pagoda
#

thats getting called in my physics substep, its being called 200 times every fixed update 😭

rocky canyon
#

i havent done car mechanics in quite a while so im a bit rusty

#

but last time i did something lkke this was for losing airpressure

#

and it was a really small decimal

rocky canyon
#

f Unity is doing ~50 fixed updates per second → that’s 200 * 50 = 10,000 calls/sec. No wonder your tires are going nuclear 👀

#

u can use ur substep as a factor for ur values

#

tireTemperature += (heatGain / stepCount) * Time.fixedDeltaTime;

#

(heatGain / stepCount) shuld normalize it abit

#

that would give a value closer to what i was mentioning earlier.. like .000x

languid pagoda
#

if (heatGain > 0f)
tireTemperature += heatGain * deltaTime;

deltaTime is defined as Time.fixedDeltaTime / 200(number of substeps).J shouldnt that be enough?

#

Ill give it a try now tho

#

Thanks for your advice!

rocky canyon
#

ohh so u are already doing that

#

ur just manipulating the deltaTime before pushin it thru

#

odd way of doing that imo lol

#

it would work but its a bit confusing

#

b/c deltaTime now doesnt actually mean Unity's DeltaTIme

#

could be throwing off code further on down the line

#

i'd use my ownvalue like that factored value first

languid pagoda
#

but setting the heating coeffecient really low actually made it work!

rocky canyon
#

and then use regular delta

languid pagoda
#

so thank you

rocky canyon
#

happy to help

#

may want to make u a debug panel to log the values real-time

#

on ur game..

#

would really help visualize whats happening as u play-test

languid pagoda
rocky canyon
#

ohhh awesome!

#

thats the good stuff

#

i love that bug

languid pagoda
#

i been fighting with it for weeks

#

do you know how to fix it?

rocky canyon
#

i think its Windows

languid pagoda
#

LOL

rocky canyon
#

nope

#

i fight it myself

languid pagoda
#

its visual studio 😭

rocky canyon
#

ohh u may be right..

#

havent seen it since i been using code more often

languid pagoda
#

yeah im about to switch to rider over it tbh

quartz jasper
#

I make code with transform with small "t" and it tells me to change to big "T" and once I do it it gives me even more errors

rocky canyon
#

what was the actual error?

ivory bobcat
#

Show the suggestion/error

quartz jasper
#

Assets\Character\CharacterMoving.cs(13,12): error CS0246: The type or namespace name 'transform' could not be found (are you missing a using directive or an assembly reference?)

#

the letter t in line 13 character 12

ivory bobcat
#

Ideally, you'd use the capitalized Transform if you're declaring a member. Lowercase if you're referring to the transform property

quartz jasper
#

It tells me to change it in line 13 character 12 and once I do it it gives me even more errors

rocky canyon
#

show that line of code

naive pawn
#

let's not play a game of 20 questions

#

you need to give context

#

show what you're actually trying to do

quartz jasper
#

not sure if the code works but it my first code I made myself to learn coding better, I will send it rn

ivory bobcat
#

How to post !code

#

Bot has been behaving strange lately

quartz jasper
#

!code

radiant voidBOT
quartz jasper
#
//using UnityEngine;

public class CharacterMoving : MonoBehaviour
{
    public float walkSpeed = 5f;
    public float runSpeed = 10f;
    public float jumpForce = 5f;
    public float gravity = -9.81f;
    private CharacterController controller;
    private Vector3 velocity;
    public transform groundCheck;
    public float GroundDistance = 0.4f;
    public Transform groundMask;
    private bool isGrounded;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        controller = GetComponent<CharacterController>();
        if (groundCheck == null)
        {
            groundCheck = transform;
        }
    }

    // Update is called once per frame
    void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + Transform.forward * z;

        controller.Move(move * walkSpeed * Time.deltaTime);

        velocity.y += gravity * Time.deltaTime;
        controller.Move(velocity * Time.deltaTime);

        if (Input.GetButtonDown("Jump") && isGrounded)
        {
            if (Input.GetKey(KeyCode.LeftShift))
            {
                velocity.y = Mathf.Sqrt(jumpForce * -2f * gravity);
            }
            else
            {
                velocity.y = Mathf.Sqrt(jumpForce * -2f * gravity);
            }
        }
    }
}
#

is my first code I made myself its janky

fickle plume
rocky canyon
#

guessing its this

quartz jasper
#

ok let me check

naive pawn
ivory bobcat
naive pawn
#

you have more issues (as spawn pointed out) but you have to solve issues top to bottom

rocky canyon
#

hehe.. not too bad if it is indeed ur first script tho

quartz jasper
#

it gives me error still

rich adder
rocky canyon
#

u actually need this

naive pawn
rocky canyon
#

right now its commented out

quartz jasper
#

no I wrote it in discord accidentally

#

in vs code its not commented

rocky canyon
#

ohh well thats confusing af

quartz jasper
#

I'll try to remake code

#

or maybe I should give up and copy from internet

rich adder
#

Vector3 move = transform.right * x + Transform.forward * z;
lowercase t when you want to use the property
big T when declaring it as field / local var

rocky canyon
#

if u wanna do ur self a disservice than sure

rocky canyon
#

calm down now

dusty umbra
#

[SerializeField] private - one low

rocky canyon
#

his first script.. lets not overwhelm him

#

he gotta atleast learn how references/variables work to begin with

rich adder
#

and a configured IDE hopefully

quartz jasper
#

Can I make this script on playmaker?

rich adder
#

no one is stopping you

quartz jasper
#

I mean can you

#

does it allow

rich adder
#

probably ? I don't think anyone in a coding channel uses it..

rocky canyon
#

its using the same code in under the hood

quartz jasper
#

I gonna try playmaker before going into text scripting

rich adder
#

Unity has also visual scripting..

quartz jasper
#

I heard playmaker more advanced

cosmic quail
rich adder
#

bro what

dusty umbra
#

idk

rich adder
#

he doesn't even know what a variable is, what are you even sending lol

dusty umbra
#

oh, fr?

#

nvm then

rich adder
#

can't you tell from random broken syntax they sent

quartz jasper
#

I removed code I remaking it

rich adder
#

you should spend the time to actually learn the basics instead of copying code

#

if anything breaks you won't know why, like it just happened

dusty umbra
polar acorn
urban chasm
#

Learn the basics like variables, data types, loops, conditionals, stuff like that

#

But seeing you dont know the difference between a type and a variable i highly recommend to not go forward until you know the basics

inner badger
#

Hello, Im trying to learn the basics of C# and Unity. Any YouTuber or online courses that you can recommend will be highly appreciated. TIA!

Note: I know I can simply do a search or ask ChatGPT for this but I'd like to know based on your experience. Something that is beginner-friendly and detailed. 🙂

inner badger
junior ivy
#

where can I learn HLSL that will work with the newest unity?

everything is outdated 😮

fierce shuttle
#

Unless they significantly changed how the pipeline and shaders works in the newest versions, I dont think shader language can become outdated, I had some shaders work in HDRP 2020+ versions that was written for Unity 5, with the biggest difference being a choice betweeen writing HLSL or using ShaderGraph (which is just a visual editor for HLSL with pipeline-specifics thrown in AFAIK)

fierce shuttle
raw shore
#

using System;
using UnityEngine;

public class Entity : MonoBehaviour
{
protected Animator anim;
protected Rigidbody2D rb;

[Header("Attack details")]
[SerializeField] protected float attackRadius;
[SerializeField] protected Transform attackPoint;
[SerializeField] protected LayerMask whatIsTarget;

[Header("Movement details")]
[SerializeField] protected float moveSpeed = 3.5f;
[SerializeField] private float jumpForce = 8;
protected int facingDir = 1;
private float xInput;
private bool facingRight = true;
protected bool canMove = true;
private bool canJump = true;

[Header("Collision details")]
[SerializeField] private float groundCheckDistance;
[SerializeField] private LayerMask whatIsGround;
private bool isGrounded;



private void Awake()
{
    rb = GetComponent<Rigidbody2D>();
    anim = GetComponentInChildren<Animator>();
}

protected virtual void Update()
{
    HandleCollision();
    HandleInput();
    HandleMovement();
    HandleAnimations();
    HandleFlip();
}

public void DamageTargets()
{
    Collider2D[] enemyColliders = Physics2D.OverlapCircleAll(attackPoint.position, attackRadius, whatIsTarget);

    foreach (Collider2D enemy in enemyColliders)
#

{
Entity entityTarget = enemy.GetComponent<Entity>();
entityTarget.TakeDamage();

    }
}

private void TakeDamage()
{
    throw new NotImplementedException();
}

public void EnableMovementAndJump(bool enable)
{
    canJump = enable;
    canMove = enable;
}

protected void HandleAnimations()
{

    anim.SetFloat("xVelocity", rb.linearVelocity.x);
    anim.SetFloat("yVelocity", rb.linearVelocity.y);
    anim.SetBool("isGrounded", isGrounded);
}

private void HandleInput()
{
    xInput = Input.GetAxisRaw("Horizontal");
    if (Input.GetKeyDown(KeyCode.Space))
    {
        TryToJump();
    }

    if (Input.GetKeyDown(KeyCode.Mouse0))
    {
        HandleAttack();
    }
}

protected virtual void HandleAttack()
{
    if (isGrounded)
        anim.SetTrigger("attack");
}

private void TryToJump()
{
    if (isGrounded && canJump)
        rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpForce);
}
protected virtual void HandleMovement()
{
    if (canMove)
        rb.linearVelocity = new Vector2(xInput * moveSpeed, rb.linearVelocity.y);
    else
        rb.linearVelocity = new Vector2(0, rb.linearVelocity.y);
}

protected virtual void HandleCollision()    
{
    isGrounded = Physics2D.Raycast(transform.position, Vector2.down, groundCheckDistance, whatIsGround);
}

protected void HandleFlip()
{
    if (rb.linearVelocity.x > 0 && facingRight == false)
        Flip();
#

else if (rb.linearVelocity.x < 0 && facingRight == true)
Flip();

}

private void Flip()
{
    transform.Rotate(0, 180, 0);
    facingRight = !facingRight;
    facingDir = facingDir * -1;
}

private void OnDrawGizmos()
{
    Gizmos.DrawLine(transform.position, transform.position + new Vector3(0, -groundCheckDistance));
    Gizmos.DrawWireSphere(attackPoint.position, attackRadius);
}

}