#archived-code-general

1 messages · Page 448 of 1

empty elm
#

Ah I figured it out. The raycast was hitting but the normal of the RaycastHit2D wasn't equal to Vector2.up so it wouldn't recognize being grounded (I have it that way to jump only on flat surfaces). My guess is that comparison to Vector2.up is sketchy because the normal vector could slightly deviate due to the imperfectness of the polygon

leaden ice
#

use something like if (Vector2.Angle(Vector3.up, normal) < 3)

empty elm
#

mhm I'm gonna just check that the ratio of y/x > 0.9 from now on

#

thanks!

weak thicket
#

hm...
If I have a string array of five channels of sound, and I want to find the bpm of each individual channel to compare.
I use a for loop to cycle through the five channels, and I utilize peak detection, caching previous peaks to compare vs time to find the bpms?

leaden ice
#

The data is strings..?

#

"string array"?

#

For BPM/beat detection people usually use FFTs.

scenic heron
#

Hello guys, just wanted to ask if this is a good movement script :) (trying to make my first 3d game) (trying to do it without looking up tutorials)

vagrant blade
#

If it works, then it works. Not following tutorials or references isn't proof of being a good developer, by the way, it's the opposite.

Also you don't need that if statement at all.

leaden ice
#

Well, removing it would change the behavior a bit. Currently the object will retain velocity when letting go of the keys. Without the if statement, it will not.

scenic heron
#

Hi again, so i'm having an issue that if i remove the
if(onGround)
{
position = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
rb.linearVelocity = position * speed;
}
The gravity on my player will slow down so it takes long to fall does anyone know why?

#

this script

leaden ice
scenic heron
#

ohhh

leaden ice
#

also why is that variable called position?

#

That's incredibly confusing

scenic heron
#

no clue why i named it that

scenic heron
# leaden ice

if i remove the 0 there the Input.GetAxis("Vertical") will in the Y axis and not Z

leaden ice
#

replace it

scenic heron
#

with what?

leaden ice
#

with the object's current y velocity

#

you don't want to change the y velocity, so you need to plug the current y velocity back in there

scenic heron
#

like this?

leaden ice
#

no

#

rb.linearVelocity.y

scenic heron
#

also i see alot of youtube vids where ppl write "rb.velocity" but there isn't an "velocity" so it outdates or smth?

#

like this

leaden ice
#

They renamed it in Unity 6

scenic heron
#

oh alr

#

do i need to make my own gravity script if i want to change the gravity in 3d?

leaden ice
#

It depends what you mean by "change the gravity"

#

you can set it to whatever you want in physics settings without any script

scenic heron
leaden ice
#

oh

#

It's because you're multiplying the whole vector by speed

#
Vector3 inputVec = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
Vector3 newVel = inputVec * speed;
newVel.y = rb.linearVelocity.y;
rb.linearVelocity = newVel;```
#

you want something like this

#

multiply the speed first, then add the old y velocity back in.

scenic heron
#

alright

leaden ice
#

(and there' no reason to have this long-lived position vector)

scenic heron
#

lol alr

weak thicket
#

sorry about that

#

so the data is an array of five floats that change with the average energy of some spectrums of an audiosource

cursive coral
#

Is there some way I can make the game delete itself in a certain situation in unity?

small jetty
#

I’m so confused on how to properly learn programming, I try to learn and I can’t figure out how to make a script to generate a room and I’ll use a tutorial

#

but then I don’t learn anything from that tutorial and it’s just me copying

vestal arch
#

do you understand the code presented?

#

perhaps you're getting in too deep, too fast, or maybe the tutorial isn't doing a good job explaining

#

consider checking out the resources pinned in #💻┃code-beginner or the junior programmer pathway on unity learn

small jetty
young yacht
#

just make sure to understand what theyre doing

prime acorn
#
public class UIManager : MonoBehaviour
{
    [SerializeField] private GameObject PostGameScreen;
    [SerializeField] private TextMeshProUGUI PostGameText;

    private void Start()
    {
        GameManager.Instance.PostGame += OnPostGameHandleUI;
        DisableUIsGame();
    }
    private void DisableUIsGame()
    {
        PostGameScreen.SetActive(false);
    }
    private void OnPostGameHandleUI(bool win)
    {
        PostGameScreen.SetActive(true);
        string s = win ? "win" : "lose";
        PostGameText.text = $"You {s}!";
    }
}

Why in the world would PostGameScreen be null in OnPostGameHandleUI? I set it in the inspector and it isnt null in DisableUIsGame, when I look at it in the inspector. The reference is also still there when it errors with PostGameScreen as null

vestal arch
#

is it perhaps from a separate instance of the component?

prime acorn
#

Cant be I initialize it as a singleton if there was another instance this would get destroyed, but just in case I double checked my scene and there is no wnd instance

vestal arch
#

it's.. not a singleton though?

prime acorn
#

Well I omitted the 500 lines that shouldnt impact this

private static UIManager _instance;

public static UIManager Instance
{
    get
    {
        if(_instance == null)
        {
            Debug.LogError("UIManager Instance is required but not set!");
        }
        return _instance;
    }
    set
    {
        if(_instance != null)
        {
            Destroy(_instance.gameObject);
        }
        _instance = value;
    }
}```
#

and then Instance = thisin awake

vestal arch
#

that's a weird way to write a singleton lol

#

destroying the old one instead of the new one

prime acorn
#

Yeah I usually do destroy the new one I was just thinking maybe thats part of the issue since it isnt supposed to persist over scene changes and I want that if it DOES persist for some reason it takes the one in the new scene not the old because the old def doesnt have the references set

vestal arch
#

well validate the claim that it's the same one
add a log to check at the top of OnPostGameHandleUI, something like Debug.Log($"PostGameScreen == null: {PostGameScreen == null}", this);

vestal arch
prime acorn
vestal arch
#

ok, try clicking the log and see what instance it takes you to

prime acorn
vestal arch
#

did you exit play mode

prime acorn
#

not yet

vestal arch
#

turn error pause on or something and do it while still in play mode

#

oh wait uh

#

double click it?

prime acorn
#

opens the code

mossy snow
vestal arch
#

ah yeah that

mossy snow
#

clicking on the error won't take you anywhere because the UIManager that throws the error no longer exists by that point

vestal arch
#

definitely what reeper said

prime acorn
vestal arch
prime acorn
#

I never heard a singleton needs to be persistent before, only single, hence the name

vestal arch
#

which is why the typical pattern is to destroy the new duplicate; it's invalid because there's already an instance

#

the non-persistence part isn't the part antithetical to a singleton, it's the part about making a new one to replace the old one

prime acorn
#

Well then how would you call what I want where I have a manager unique to a scene like this, since I aint searching and finding UI objects on every scene change manually lol

vestal arch
#

well, you have a gamemanager singleton, don't you?

#

i'd put the UIManager reference on the GameManager, and then on UIManager's Awake, i'd set that reference

prime acorn
#

Yes and? It doesnt know the UI objects that dont exist in the main menu but do exist in the game either

vestal arch
#

you would have UIManager inform the GameManager of its existance

prime acorn
#

But still noone knows the references to the GOs

#

Because both get Created in the menu

#

but then the references live in the game scene only

vestal arch
#

i honestly have no idea what you're talking about

#

the UIManager knows of its own reference
it tells the GameManager about that reference

#

then everything else can ask the GameManager for the reference for the current scene

prime acorn
#

I still need something that only lives in my game scene that informs the UIManager about its objects, that or manually go through the object tree and find what Im looking for

prime acorn
vestal arch
#

it does exist though

prime acorn
#

I start the game I get into the menu the menu doesnt have a PostGameScreen I go into the game the game has a PostGameScreen

vestal arch
#

if a UIManager exists, then its reference also exists...?

prime acorn
#

Im not talking about the reference to a UImanager

#

Im talking about the reference to an object that the UIManager accesses

vestal arch
#

UIManager would be in the same place with the same references

prime acorn
#

but then we are exactly where I am now

#

Where I have a UIManager in the menu and one in the game

vestal arch
#

what would change would be that UIManager doesn't treat itself as a singleton

prime acorn
#

The one in the menu handles menu UI the one in the game handles game UI

vestal arch
#

that isn't really relevant to what im saying

#

i understand your situation

#

nothing would move

#

but the UIManager isn't a singleton, so it shouldn't present itself as a singleton

#

what im offering as an alternative would be to have UIManager inform the GameManager singleton about what instance of UIManager is active

mossy snow
#

it seems like UIManager is becoming a god class that does different things based on the context it exists in. Why not split it into MainMenuUIManager and GameUIManager? Then you can use direct serialized references and avoid this code smell

prime acorn
# vestal arch what im offering as an alternative would be to have UIManager inform the GameMan...

You mean like this?

public class GameManager : MonoBehaviour
{
    private UIManager uiManager;
    public UIManager UIManager
    {
        get
        {
            if(_instance == null)
            {
                Debug.LogError("UIManager Instance is required but not set!");
            }
            return uiManager;
        }
        set
        {
            if(uiManager != null)
            {
                Destroy(uiManager.gameObject);
            }
            uiManager = value;
        }
    }
}

UIManager ->

private void Awake()
{
    GameManager.Instance.UIManager = this;
}
#

forgot a reference but you get what Im trying

vestal arch
#

it's not marked DDOL or anything, is it?

#

you don't necessarily need the check in the setter

#

but yeah that's the gist of what i mean

prime acorn
vestal arch
#

ah, i mean the UIManager

#

was vague

prime acorn
#

No that one isnt

buoyant copper
#

Hello, i have a small question about scriptable object, in my project I have an ability scriptable object with a variable called abilityName, is there a way to connect this name with the name of the asset? Like when creating a new abilitySO the name of the file is the value of the abilityName variable?

steady bobcat
vestal arch
#

!code

tawny elkBOT
vestal arch
#

anyways, rb.linearVelocity is relative to world space, not local space

patent crown
#

hi
I am new to the server
as a new DevOps engineer in the field
do you recommend going to DevOps for websites, mobile or games
but how can DevOps work in games 🤔

cosmic rain
astral nexus
#

It's more of a general mindset question, but it's kinda coding related.
I feel like I've lost the ability to use throwaway and spaghetti code to just iterate and test things and finish products. This problem leads me to burn outs and premature optimizations/analysis paralysis instead of making and finishing games. What can I do to confront it? I want to finish anything, but I always scrap my code and rewrite it, because of this problem. I understand that no one cares about code in my game, if the game is not lagging/crashing ofc, but I feel like I'm obsessed with code quality, even tho I can't achieve this quality I want, lol.

cosmic rain
# astral nexus It's more of a general mindset question, but it's kinda coding related. I feel ...
  1. Think of your code/systems architecture before writing any code. Write it down in details on paper. And avoid deviating from it when actually implementing it.
  2. Break down the development into tasks. Use services like Trello to keep track of tasks and their progress.
  3. Use version control and periodically check in/commit changes when finished working on a certain part of a system/feature. This would give you a degree of freedom to experiment with your code, since you can always rollback to the last working version.
  4. Instead of rewriting systems entirely, think of how you can refactor them to fit whatever new feature you need(and potentially other new features). Basically learn to make your code extendable.
#
  1. Start simpler. Work on a simpler "challenge" project and get it through to the end(release on some store). It needs to be simple enough for there not to be much stuff to rewrite. This would give you a feel of getting through all the stages of development and how to keep it together.
#

Other than that, it's normal to rewrite your code many times until you're somewhat satisfied with it. Everyone goes through that.

#

Accept it as part of the development process and realize that development is hard.

astral nexus
# cosmic rain 1. Think of your code/systems architecture before writing any code. Write it dow...

I have huge problems with planning too, because I can code only when I code things right here and right now (if it makes sense, heh) and planning just makes my head empty, because I don't know what I need in what order for now.
Like, I know what I want to make on "design side" (like what mechanic/system do, how they interact at high level, etc.), but what, how and when to code first - I just feel empty until I start to do it without planning.

cosmic rain
night harness
#

Dumb side answer but maybe even ban yourself from certain c# features to enforce very primitive composition. Over engineering is a lot harder to do without the necessary tools

astral nexus
cosmic rain
white burrow
#

Just getting into Unity but coming from a .NET dev background. There any good resources on architecture and patterns for Unity e.g. how to separate a project into UI, main game code, etc.

#

Seem to have gotten myself into a situation where the game commonly hangs, and it's definitely due to a poor understanding of coroutines and the way I've pipelined the different classes together

cold parrot
# white burrow Just getting into Unity but coming from a .NET dev background. There any good re...

There are no good resources, most stuff you find is dogmatic of misleading. What you should aim for is a progressive architecture that can grow from simple to advanced as the project grows. Most complex, mature games use, Dependency Injection, MVP/MVVM patterns, Message Busses and data oriented programming principles as the need comes up. Unity encourages some patterns more than others and at different levels of project complexity. It is important to understand the dead ends and issues with overly idealistic application of any programming patterns. Generally what is true in a simple CLI or CRUD applications does often not work out well in a context where object lifecycle, performance and UX is very intertwined, dynamic and complex. Most projects cannot be developed along a single pattern or principle. it often makes sense to think of a game as a collection of modules that cooperate, each having a potentially different, but use-case optimized architecture. On early trap is over-abstraction and not realizing the value of GameObjects for debugging and iteration speed.

#

However doing all that (big patterns) from the start or in small projects is counter productive. One thing you can do right away is keeping UI/View and game-logic separate (MVP works well) and focus on one-directional data/control flow. The more you keep logic flow decoupled from data (configuration, prefab structure, scene structure) the easier it is to migrate existing features to more mature systems.

eager lichen
cold parrot
eager lichen
#

yep but that's learned with experience, practicing with them just makes you a better programmer in general

steady moat
# white burrow Just getting into Unity but coming from a .NET dev background. There any good re...

Experience is your best bet. Most resource you find is self-thought and poorly "battle-tested". This is without talking about how each game context varies greatly.

That being said, you have the following that are the most common:
State machine,
Observer,
Strategy,
Flyweight,
Singleton,
Factory,
Service locator

If you have more precise question, we would be happy to help you explore more in depth what "pattern" you could attempt to use.

steady moat
eager lichen
#

regardless the other advice is good, no need to hammer that point

sick cove
#

question about decals. I have a mechanic where when enemies explode, they leave behind paint splatters on the ground and walls, however when a second enemy explodes, the decal gets placed below the previous one instead of above. does anyone know a solution? so far i've tried playing with it in the hierarchy, order of children and offset, however none of them seemed to work.

dusk apex
sick cove
#

I spawn them in using a script.

#

Where I set the transform and other stats

#

3d

#

I'll get the screenshots in a sec,

dusk apex
#

If it's not an issue with code, you should move your question to #💻┃unity-talk (seems unlikely code related)

sick cove
#

aight. i'll see

vital granite
#

Need advice modifying an auto scroll script
https://paste.mod.gg/ixcnegkfjdpo/0
in the ScrollToSelected function it gets the position based on which selectable the user is currently on out of the total selectables in the scroll view
But this causes issues if I have an object which holds two selectables inside of it in the same general y pos causing the 1st selectable to appear slightly higher than the 2nd one
Any recommendations on how I could change this cal so it doesn't do that?

vital granite
#

Wait I think I got an idea how to work around it

somber tapir
#

I got an Interface like this:

public interface ISpawnable<T>
{
    public event Action<T> OnDeactivated;
}```
Is there a way to get a reference to any implementation?
I can't make the class that holds the reference a generic
dusk apex
#

This may have changed though with more modern C# but ideally, you'd have the implementation done elsewhere

cold parrot
#

one should never have a situation where the concrete implementation of an interface matters, defeats the point of having an interface. in cases where its a valid thing to want (say during serialization) the way to go is reflection. This is complicated and slow enough to make you think hard what you are doing.

chrome sage
#

sorry, I posted this in #📱┃mobile but this seems more active... has anyone asked about how to emulate the OnMouseHover callbacks for mobile? what would be the equivalent? say I had a fight button that would change to forecast of the fight result on hover (win fight / lose fight) then the player presses that (win fight / lose fight) button. would this be possible to 1:1 translate from a mouse to touch?

cold parrot
chrome sage
cold parrot
chrome sage
cold parrot
#

if they do they do so at work and get paid to care 😉

dusk apex
#

Or the class needs to be generic

somber tapir
#

the type can very. I prefer not to make the class generic, but I think I've got no other choice

dusk apex
thick terrace
#

do the possible values of T have anything in common? maybe make another interface so you can access the shared behaviour through that, like make your field an ISpawnable<IDeactivatableThing> or whatever you want to name it

dusk apex
#

If so, they could probably forgo the generic interface and simply use the concrete super type directly in the interface.

thick terrace
#

you could put a type constraint on it and it'd work either way

somber tapir
#

ahh close, but that causes other issues.

Basically I have an UI grid with cells. Currently, it's for displaying damage texts (like in WoW) with one text per cell so they don't overlap.
When a text is spawned it gets the position from the grid and the cell holds a reference to the text and starts listening to the deactivation event.
Once the text is deactivated again the cell gets cleared for another text.
The Interface is generic so other classes who subscribe to the event don't have to cast first.

#

I think I just make a second Interface that is not generic

wicked seal
#

Hi guys, I have a kinda easy question, I'm currently looking to achieve using the same gameObjects on different unity scenes (So I dont have to copy paste the player and the screen controller for each scene), I heard about additive scene loading but I couldn't find a good tutorial on the scope of that functionality. How would you guys approach that?

chrome sage
# wicked seal Hi guys, I have a kinda easy question, I'm currently looking to achieve using th...

This is Part 44 of Make a Game Like Pokemon Series in Unity. In this video, we'll look at a concept called additive scene loading which will allow us to smoothly go from one scene to another without switching them. It loads a scene without unloading currently loaded scenes

Join my Patreon to support this series and get access to the Complete Pr...

▶ Play video
graceful basin
#
//....existing Update() code
                if (!isCollected && Vector3.Distance(transform.position, worldTarget) < 0.1f)
                {
                    isCollected = true;
                    CollectScrap();
                    Destroy(gameObject);
                }
                break;
        }
    }

    void CollectScrap()
    {
        scrapManager.AddScrap(scrapAmount);
    }

does anyone know why my AddScrap(scrapAmount) get's called twice sometimes? my scrapAmount is 5 and sometimes in my ScrapManager I see that 5 was added 2 times. I thought with the "isCollected" I'd solve that

dusk apex
#

Log the name of the object that was destroyed

steady bobcat
#

some logs may help but using breakpoints with a debugger will let you see exactly what is calling this function and when

graceful basin
#

issue is, it's for a game jam. and I don't have too much time to debug this forever :/

wicked seal
chrome sage
chrome sage
low spear
#

Hi, font question... How many fonts and fallbacks do people typically have to support the majority of characters from various languages? For example, if you were launching a game which showed user's Steam usernames (which might be in various languages) then do you typically have long font fallback chains to try and have support for as many as possible? Has anybody done this in a shipped project that can offer guidance here? Thanks!

lean sail
leaden ice
#

And/or use a bootstrap scene and DDOL objects.

steady bobcat
#

A good idea is to automate showing all your game text in all langs in a scene to check for problems

somber tapir
low spear
# steady bobcat Games i work on have about 10-25 langs and we have a main english oriented font ...

Right, ok. At the moment our game has no localization (yet), so it's English, but, we're an online game which displays Steam usernames - which could be absolutely anything in terms of character sets/glyphs... so I guess we need to add fallback support for the common languages as you say. How do you know what characters to put into the SDF for the other languages, or do you leave them all on some specific font setting?

steady bobcat
#

The fallbacks i leave on automatic to be filled as needed

#

These are mobile games and i did experience a lot of lag when trying to load a lang list (putting a large load i presume on tmp to add characters) so I also made a system to "pre warm" fonts with their name (you can add characters to fonts whenever you want at runtime)

low spear
#

sorry, bit new to some of this... when you say "pre warm" do you mean make sure some character ranges are rendered into the SDF at editor time first?

steady bobcat
#

If you just have them as dynamic its probably fine. The issue i mentioned is probably due to trying to show loads of stuff at once and being on mobile.

low spear
small jetty
#

would a infinite dungeon game be too advanced for mh second game? my first one was flappy bird and I learnt quite a bit

cosmic rain
small jetty
modest locust
#

does having too many if checks being called in update reduce frame rate?

#

my game is tweaking and all i have is a cube, a plane, and the player.

#

so either my laptop sucks or calling around 10+ if statements is a bad idea

cosmic rain
cosmic rain
#

If you have performance issues, you should use the profiler to investigate them.

dusk copper
#

I have been stuck at this problem for a few days

#

pls send help

cosmic rain
#

Here you go: "help"

small jetty
#

everytime i try to program something involving some math it makes zero sense 💔 what should i do

dusk copper
cosmic rain
small jetty
lean sail
small jetty
#

thank u!

modest locust
#

i don't know what i'm looking for

#

it is quite long though

lean sail
cosmic rain
tawny elkBOT
sharp garden
#

apologies if this is the wrong channel!
in my game my player character can travel along splines ('grinding'), and I call SplineContainer.EvaluateTangent to calculate the direction the player should travel along the spline.

but for some reason, splines with certain shapes (in particular the right-angle example attached) have strange results when calling EvaluateTangent, but only at certain points along the spline. for example, with the pictured spline, the tangent direction points in the wrong direction in the circled area, but outside that area it is along the spline as expected.

#

it also only happens when I first calculate the tangent using the player's 'anchor point' (nearest point on the spline)

#

if I calculate it using the player's current position (while we are grinding from a 'safe' point on the spline that doesn't cause issues) it works as expected (purple lines are the tangent/travel direction at each point on the spline)

#

but if I calculate it initially using the 'anchor point' I get very weird results like this. the tangent is the complete wrong direction and the player moves very erratically because of it.

#

I've verified that the 'anchor point' is correct each time, its the nearest point on the spline as expected, so I have no idea whats causing this

#

(better example of the last thing, the yellow sphere is the anchor point and the green line is pointing in the unexpected tangent direction)

quartz sun
#

IVE DONE ITTTT! I finally created a rail grinding mechanic within my Unity 2D project ! I put this on github for anyone to try out for themselves. Please feel free to give me your feedback an thoughts on it. Its still a prototype but this is basically for anyone who was in the same boat as me and unable to find a proper explanation or forum to help figure out where to start! https://github.com/lsclarke/Unity-2D-Rail-Grind

GitHub

Contribute to lsclarke/Unity-2D-Rail-Grind development by creating an account on GitHub.

fiery steeple
#

Are there cases where events aren't declared as static ?

night harness
#

Depends on the person and context but from what Ive personally seen there usually not static

night harness
#

Really depends on the usecase

fiery steeple
#

Are you familiar with the game The Escapists 2 ?

#

Like I'm trying to create a daily routine system, and I wrote this, so I was wondering if I should leave it static or not 🤔

night harness
#

Heads up that no modding talk on this server if that’s what this is

#

unless just comparison

fiery steeple
#

in Unity

quartz folio
#

I almost never create static delegates, as they're often a really great way to create a leak

thin aurora
#

If you are making static events, a better approach might be an event bus

#

Considering it appears your events need to be tied to multiple not directly shared instances

quartz folio
#

If a subscriber fails to unsubscribe then it and everything it references will remain in memory

night harness
#

For any “global” reference that might live on a singleton I prefer to make them static for reduced code length and the implication that if it’s a static reference on a manager it’s ok to touch but yeah I have my own personal solution to managing static events that makes leaks less of a problem.

Overall something like this could just exist on a singleton if your worried about using statics though

fiery steeple
thin aurora
night harness
#

To answer your original question though for example if your prisoners has events you may prefer them to exist on each instance

fiery steeple
#

I'm really confused when for a single question there are multiple answers 😤

late lion
# fiery steeple Are there cases where events aren't declared as static ?

The events you've made so far are high level game events, so it doesn't make as much sense to tie those to a specific instance of a class. But there are many cases where you'd want instance events.

For example, if you have a Button script, you probably want to be able to subscribe to when a specific button is clicked, not just any button.

fiery steeple
late lion
# fiery steeple But couldn't that still be made through static events by passing the button itse...

It can. But it's very inefficient, both in performance and the amount of code you have to write. The listener would look like this:

[SerializeField]
private Button myButton;

private void OnEnable()
{
    Button.ClickEvent += OnButtonClickEvent;
}

private void OnDisable()
{
    Button.ClickEvent -= OnButtonClickEvent;
}

private void OnButtonClickEvent(Button button)
{
    if (button != myButton) return;

    Debug.Log("My button was clicked!");
}

versus an instance method:

[SerializeField]
private Button myButton;

private void OnEnable()
{
    myButton.ClickEvent += OnButtonClickEvent;
}

private void OnDisable()
{
    myButton.ClickEvent -= OnButtonClickEvent;
}

private void OnButtonClickEvent()
{
    Debug.Log("My button was clicked!");
}
#

Imagine if you had 100 buttons and a listener for each of those buttons. With a static event, clicking a single button would mean notifying 100 listeners, where all but one do nothing but compare which button it is and ignore it. A lot of wasted time. Versus just notifying one listener.

fiery steeple
late lion
#

But note, that event still doesn't have to be static necessarily. It could still be an instance event, just on a class where there is only one instance, like a GameManager singleton.

fiery steeple
late lion
fiery steeple
late lion
fiery steeple
late lion
#

Events are useful because they let you decouple scripts. It means I could write a KillFeed script that just listens to player killed events and that way the Player script doesn't need to notify the KillFeed directly or even know it exists.

This holds the same whether the event is in the Player class or in a GameManager class.

fiery steeple
#

but once notified what it does with that ?

late lion
#
public class KillFeed : MonoBehaviour
{
    [SerializeField]
    private TMP_Text killMessageBox;

    private void OnEnable()
    {
        GameManager.Instance.PlayerKilledEvent += OnPlayerKilledEvent;
    }

    private void OnDisable()
    {
        GameManager.Instance.PlayerKilledEvent -= OnPlayerKilledEvent;
    }

    private void OnPlayerKilledEvent(Player victim, Player killer)
    {
        killMessageBox.text += $"{killer} killed {victim}!\n";
    }
}
#

For example.

#

If the event is only an instance event in the Player class, then this script will have to somehow get every player in the match, so it can subscribe to their event.

#

If players can join and leave the match at any point, it would probably have to subscribe to another event, PlayerJoined and PlayerLeft, where it then subscribes/unsubscribes to their Killed event.

#

A lot more work compared to the single event in GameManager, like the example.

fiery steeple
#

So if it's on Player, that means the KillFeed must subscribe to every event of every player ?

late lion
#

Yes, if it's a non-static event in Player, that means every player has its own event with its own set of listeners, and if KillFeed wants to be notified of every player's event, it needs to get a hold of every player at some point in order to subscribe to their event.

fiery steeple
#

sa the event can't be saved on Player then

#

it has to be on a centralized class

#

like the GM

#

So according to you my OnDailyRoutineChange event should or shouldn't be static ? 🙂

stoic dawn
#

hi i have a collision problem do i ask here?

late lion
# fiery steeple So according to you my ``OnDailyRoutineChange`` event should or shouldn't be sta...

In this case, it doesn't matter as much as the example we've been talking about. There is only one instance of DailyRoutineManager, since it's a singleton. The only difference is you'd access it through the Instance instead. But it's recommended to do that, since when the singleton is destroyed, after play mode exit, the event is cleaned up with it. If it's static, it stays alive, even during edit mode. And if you have domain reload disabled, as is recommended, static events are not automatically reset between plays in the editor.

fiery steeple
late lion
fiery steeple
# late lion It's recommended.

Do you have good resources (mainly youtube if possible) that talks more in depth about everything you taught me please ? 🙂

late lion
unreal birch
#

Something very strange is happening ot my text, I don't even know how to google for it - any idea what this is? The text is fine in English...

#

But when I swap over to another language, it starts stacking it on top of each other, even in-inspector:

#

I've got like hundreds of text elements but this is the first time I'm seeing it, using same localization tools everywhere... I'm at a complete loss

thick terrace
unreal birch
#

I thought so too, but it seems like it's working fine everywhere else I have text in Polish, it's just some very specific elements that seem to be broken... 🫠

thick terrace
#

if you paste that same string into other text components, does it render OK?

unreal birch
#

Good idea, it seems to keep the weird stagger in other elements too - so I assume there is something wrong with the string?

thick terrace
#

yeah, maybe it's got some invisible characters or unusual variants of the normal characters in there

#

considering it's broken in the Unity text field too, that seems likely!

unreal birch
#

Does it look like there's anything off about this code snippet maybe? I was using it elsewhere (like the text under the broken header) and it worked fine, but maybe it's causing the issue for some reason:

` infoHeaderText.text = string.Format("{0} - {1}",
LocalizationTools.Instance.GetLocalizedString("LocationTextTable", "informationTitleKey"),
LocalizationTools.Instance.GetLocalizedString("LocationTextTable", locationTemplate.LocationNameKey)
);

    infoFactionText.text = string.Format("{0} - {1}",
        LocalizationTools.Instance.GetLocalizedString("LocationTextTable", "informationFactionTitleKey"),
        LocalizationTools.Instance.GetLocalizedFactionName(locationTemplate.LocationFaction)
    );`
thick terrace
#

that looks harmless to me, i think it's more likely the problem is in the localization sheet itself

unreal birch
#

You were right - I don't know why or how (it looked the exact same) but when I erased the location name and typed it again it got fixed... thanks for the hint, I'd have been stuck on it for forever ❤️

timber rampart
# fiery steeple What's that (Event Bus)?

It's a pattern, also called Event Aggregator Pattern. I got some static EventHub class, which contains static Actions. Other components can listen to them or invoke them, without having to know about one another. It is fully agnostic. You could even do things like listener cleanups on scene change etc since all events are held within this "Event Hub"/"Event Bus". It offers separation of concern. You can also extend this, to give certain listeners priority when executing callbacks for example.

You do not want to overuse this though: This is a good pattern very well suited for your main game events: Scores have changed, the user has changed settings, a sceneload will soon happen, the scene has finished loading... i.e. things that lots of things might want to know about. For smaller events, some local Action and a direct reference to listen to it is probably preferable.

modern epoch
#

Can you have multiple pathfinder objects in a scene

#

My second pathfinder isn't showing an outline

frail hawk
#

I have an issue with Cinemachine after updating from v2 to v3, and I'm not sure where I'm getting it wrong. I've got a CinemachineOrbitalFollow component with BindingMode set to LazyFollow and RotationControl set to Hard Look At.
I'm trying to simply rotate it, and this used to work in v2:
orbitalTransposer.HorizontalAxis.Value = 90;
That seems to only rotate the camera by roughly 45 degrees, while 180 doesn't seem to do anything. HorizontalAxis' Range is set to (-180, 180) and Wrapping is enabled. I feel like I'm just misunderstanding what it's supposed to work like now, but I can't find a proper solution or a better way to hard set the rotation.

vestal arch
#

share your !code properly please

tawny elkBOT
modest locust
#

so use the backquotes?

modern epoch
#

Can you have multiple pathfinder objects in a scene

vestal arch
modest locust
#

oh ok ok.

vestal arch
#

ok what was your question?

modest locust
#

yeah, so, it basically runs really slowly

#

despite there being pretty much nothing in my scene. I was wondering if that was because my code is not very good

vestal arch
#

you seem to never reset y?

modest locust
#

oh that's a good point

#

i don't

#

but then again is that neceseary? because when i jump it get's set to a value

#

and on wall running it's 0

vestal arch
#

it seems like you'd be trying to force the CC into the ground. i haven't used CC so im not sure whether that's an issue or not

#

anyways you should debug your values

modest locust
#

i'll try reseting y to 0 on ground check, unity might be able to handle larger values over 32 or 64 bit

#

yeah that didn't change anything

#

i'll try debuging and other things. but for some reason it says i have 900 vertecies in my scene... so maybe it's something with that

vestal arch
#

in any way

#

unity doesn't really handle the values at the bit level, c#/.net does that
and floats don't use the 32 bit integer limit, their limit is a bit more complicated. you could argue floats don't have a limit at all, in some senses

naive swallow
versed gyro
#

I have (what I think is) a pretty niche issue, if someone could help me out that would be amazing.

I'm currently working on a top-down 2D game. I have a gun-like object that needs to fire particles in the direction of the mouse from the player, but the particles need to:

  1. have an initial right velocity that comes to a complete stop
  2. move independently of the player, ie based on world position

For 1, I used limit velocity over time to world to draw a curve that starts at the initial velocity and ends at 0.
For 2, I set the simulation space of both the particle system itself and limit velocity over time to world.

While this works for the requirements, the particles can only be fired in a single direction because velocity over time is set to world simulation. I tried to set velocity over time to local, but this causes the particles to move with the character. Is there any way to have the damping effect while also being able to change the direction that the particle system is firing at? The only solution I can think of is to create a new instance of the particle system every time the player fires, but this seems inefficient.

late lion
versed gyro
#

actually if there's a way to change the velocity over lifetime values via script, I could just calculate the values needed for a rotation manually

late lion
# versed gyro

Oh, that's Velocity over Lifetime. If you set Linear to 0, 0, 0 and just have the speed modifier curve, you get the effect you want, as far as I can see.

#

The speed modifier will change the speed of the velocity without changing its direction. So the particles will have whatever direction they started with.

versed gyro
#

is there a way to set the linear velocity of the particles outside of this module?

late lion
#

Yes, start speed in the main module.

#

Then it will go in whatever direction is dictated by the emission shape.

versed gyro
#

this is what I have now, I've tried all of the emission shapes and they all seem to spread out from the transform of the particle system

late lion
#

Change the shape to a cone, make sure it's rotated to face the same direction as the player's gun and that it's a child of it so it follows it.

versed gyro
#

ah ok, I think that's the closest I'll get. I'll try messing around with the cone shape some more

modest locust
modest locust
#

I’m starting to think I just have a really bad laptop

ocean hollow
#

TIL that there is a difference between comparing objects and variables

vestal arch
ocean hollow
#

yeah thats what i meant

vestal arch
#

there still isn't really a difference

vestal arch
#

that's not comparison

ocean hollow
vestal arch
#

ok, what do you think the difference is...?

ocean hollow
#

one uses Object.operator and the other use int.operator

vestal arch
#

that's because of the types of the things you're comparing

ocean hollow
#

yeah, i was saying that i never knew that c# had to specify a difference

vestal arch
#

it's the same difference as 1 + 2 and Vector2.up + Vector2.right are different lol

#

the separation isn't in "objects vs variables"

#

they're both comparing values with the same mechanism, the difference is that they're of different types

ocean hollow
#

yeah... that's what i was talking about...

#

i just never knew it worked like that

#

i always thought that all == were created equal (pun intended)

vestal arch
#

well you gotta define how to compare stuff, otherwise you get locked into a single operation that works across everything that might not be useful in specific circumstances (see: java, js)

#

this is called operator overloading, it treats the operator as like a method
c#, c++ support it directly
python supports it via dunder methods (it also has a non-overloadable is that's like java's == and js' ===)
java just has a specific method equals to use instead of operator overloading
js just doesn't have a standard

quiet kestrel
#

Does anyone know how to make this effect where you enter a space that behaves differently from what the outside world entails?

Example EVA's Dream BBQ: You enter the huge ear and arrive at the purge event. Which isn't shown outside the ear, and there is (seemingly) no scene loading

rigid island
quiet kestrel
swift falcon
#

which is more preferred?

rigid island
rigid island
swift falcon
#

i know but which is better

rigid island
#

there is no "better" if they both do the same thing..

swift falcon
#

for better code readability

rigid island
swift falcon
#

kk

empty canyon
#

I need to some help getting a rock to shatter when hit. I have the basic code of the game object being destroyed on it, but I want to add a shatter effect to make it more dramatic. Thing is that the rock is shattering when I load in. Above is my Collision Handler code with how it works(I added a unique tag to breakable objects is how it works). The other is a separate script that breaks the rock and codes its force. Above is also a video showcasing my issue

#

Here is my "CollisionHandler" script which is functioning fine and shows how it works and the other is my "Break" script that activates the shatter effect

steady bobcat
#

also tags are bad long term so try to move to your own components for this data instead

empty canyon
#

I tried calling Break object within Case “Breakable” but it didn’t help not change anything

empty canyon
steady bobcat
#

fuel for example can be:

if(collision.gameObject.TryGetComponent(out Fuel fuel))
{
    AddFueld(fuel.amount);
}
steady bobcat
#

gah mb im also playing fo76 😦

empty canyon
steady bobcat
#

its probaby better that the destroyable things do the reaction on their end (e.g. if collision entry/trigger entry is the player then destroy)

drifting grail
#

Does anyone know how the walls are set up? i imagine the floor and the ceiling above the walls is made using a tilegrid, but the walls confuse me

night harness
#

Dunno forsure but i could see it being a custom tilemap editor where like you’d be painting with the top/floor sprite in mind but your painting prefabs with the walls and such setup

#

Or just manually authorised tbh

night harness
#

Kinda yeah, but in a 3d space

#

I would not be surprised if the workflow was a lot more primitive than you might assume but that’s a guess

drifting grail
#

I can't find any documentation on it

night harness
#

Ye

#

Unity tilemap stuff would struggle out of the box would struggle with this

#

At the end of the day it’s just a 1x1x1 grid of tiles

drifting grail
#

Maybe three stacked grids, but the middle grid (the wall grid) rotates all tiles 90 degrees

night harness
#

Not sure what you mean with the rotation stuff

drifting grail
#

now i can paint the walls in on the second grid pretty easily

#

only issue is that the tiles clip

night harness
#

Ohh i see. That can work too but my responses were based under the idea that each tile was probably a prefab containing the relevant floor, walls etc. sprite rather than each surface being a tilemap separate from eachother

drifting grail
#

order layer fixed that nvm

drifting grail
drifting grail
night harness
#

Unity 2d isn’t anything actually different from 3d

#

Gungeon is a “3d” game

steady bobcat
#

mixing sprites/normal mesh renderers isn't that bad (as long as render order is correct)

drifting grail
#

i am already mixing 2d and 3d

#

at my current skill level i don't think i could use anything off the tilemap though

royal hinge
#

Guys I tried everything all solutions I could find online and nothing worked, what is wrong with Cinemachine and why can't I use it? Unity doesn't recognize the "
using Cinemachine;" line

rigid island
royal hinge
#

Of course, installed, removed and installed again. Nothing worked

latent latch
#

would be nice for a damn 3D tilemap :(

rigid island
#

yea...sadly we only have GameObject/Prefab brush at best that works with Grid but not Tilemap.

night harness
#

I yearn to be whatever target audience the tilemap features we’re built for

rigid island
royal hinge
#

How would I use them?

rigid island
royal hinge
#

Yeah, I think so, how can I check?

rigid island
#

forgot how to search by extension in unity search

royal hinge
#

I have these files, 2 of which are Cinemachine

royal hinge
rigid island
#

in that way you have to reference the cinemachine one

royal hinge
rigid island
#

I'm saying you should check if you have an asmdef file within your scripts folder

naive swallow
#

Or in a direct parent folder of it

royal hinge
rigid island
#

I can't think of any other thing besides being asmdef since even unity wont recognize and not just ide

quartz folio
#

What's the one that's highlighted in that screenshot?

rigid island
royal hinge
royal hinge
steady bobcat
#

Probably time to show the code causing the error as its clear you did not make a custom asm def

leaden ice
#

Just as a probably relevant aside: the namespace these days is Unity.Cinemachine

royal hinge
leaden ice
#

yes

#

Your IDE should have recommended that for you

steady bobcat
#

yea in vs you can make your field or var and use the lightbulb to easily add the using statement

royal hinge
leaden ice
steady bobcat
#

!ide moment

tawny elkBOT
leaden ice
#

Sounds like it might not be

steady bobcat
#

we need a counter for this too 😆

royal hinge
# leaden ice Sounds like it might not be

No, I just started with Unity a few days ago, and spent this whole day fixing the Cinemachine bug. How would I configure VSCode? Are you talking about an extension or?

leaden ice
#

You should do that before anything else

#

it will make your life 1000x easier

royal hinge
royal hinge
craggy pivot
#

Is shader programming supposed to have autocomplete like C#? I'm brand new so I wouldn't know.

leaden ice
#

It's generally a lot more fraught. I don't think VS has any intellisense for it out of the box

craggy pivot
#

Makes sense, maybe someday!

night harness
#

(Also shaders are not c#)

craggy pivot
#

Yeah, shaderlab and hlsl

modest locust
#

rewriting my movement script a whole bunch of times until it's absolutely perfect is a good idea right?

craggy pivot
#

If it's causing problems, then sure, but if you're not making progress on anything else because of it you might need to cut yourself off

modest locust
#

I mean, it doesn't work right now, but i'm also too lazy to find out why, so I'd rather just rewrite it.

craggy pivot
#

Okay I would object to that approach

#

If you're not figuring out exactly why it's not working, then you aren't learning anything really.

#

That's more like throwing stuff at the wall and seeing what sticks

#

And if you say rewriting it until it absolutely perfect, how would you know that?

modest locust
#

yeah, so i'll look for the problem then instead. probably a better idea since it's a long script anyway.

leaden ice
#

I feel like I must be missing something obvious here. How come this works perfectly fine:

float seconds = arena.CurrentPhysicsFrame * Arena.SecondsPerFrame;
timeLabel.text = $"+{seconds:F2}s";```
I get the correct output here which is a string that looks something like "+1.55s"

But this 
```cs
timeLabel.text = $"+{(arena.CurrentPhysicsFrame * Arena.SecondsPerFrame): F2}s";```
gives me the output: "+ F2s"

It's breaking but in a way I completely do not expect.
craggy pivot
#

Is it the space after :?

leaden ice
#

🤦‍♂️ - yes it was

#

It's weird it completely discards the entire expression when you do that though

craggy pivot
#

That is weird... and weirder still at F2 actually shows in the output, because the {} is and expression block.

leaden ice
#

Yeah I get that it's breaking it's just that the way it breaks is so weird to me. I would have preferred a compile error.

craggy pivot
#

Lool, right?

vestal arch
quartz folio
#

All characters that aren't a part of the format string are copied to the result string unchanged.

pulsar belfry
#

im stuck on this error

quartz folio
quartz folio
#

Then you need to configure it. !ide

tawny elkBOT
pulsar belfry
#

i cant find external tools

quartz folio
#

That's not Preferences

pulsar belfry
#

where is it at?

quartz folio
#

Edit/Preferences

pulsar belfry
#

thanks it was already configured

quartz folio
#

Well, some part of it isn't, or else you would have highlighting and autocomplete

pulsar belfry
#

i did everything i downloaded the package on both and it was set just like the image on the website for preferences

quartz folio
pulsar belfry
pulsar belfry
quartz folio
#

You commented out your errors and let Unity compile, and you installed the .NET SDK?

craggy pivot
#

These are the extensions I have that work for me, i have no idea what makes it work exactly

#

Make sure you're signed in to vs code and that might make the .net install tool work better idrk

#

Make sure to restart vscode after installing

#

Maybe even try restarting unity, and sometimes pressing "regenerate project files" fixes stuff (I also don't know why)

rocky basalt
#

Does anyone have advice on how to lerp/tween material/shader property values? I'm using DOTween, but the values seem to "jump" instantly instead of lerp via the methods I've tried. Curious how others approach this in code

leaden ice
#

in general - the answer is to use the DOTween extension methods for materials to start a tween like normal;

rocky basalt
leaden ice
#

just myMat.DoFloat(....);

rocky basalt
#

Ahhh, thank you, this is good! No idea how I missed that!

night harness
#

Small heads up that iirc you should be caching that material property getting via Shader.PropertyToID

rocky basalt
#

Is that because the dotween coroutine is using the shader string name each frame? Or just as a optimization habit? I'm only calling the tween on occasion

night harness
#

Pretty sure both

pulsar belfry
#

ok i downloaded .net and im getting this error ``` 2025-05-12 21:44:58.991 [info] Additional information of .NET SDKs for diagnostic
Host:
Version: 8.0.15
Architecture: x64
Commit: 50c4cb9fc3
RID: win-x64

.NET SDKs installed:
No SDKs were found.

.NET runtimes installed:
Microsoft.NETCore.App 6.0.26 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.NETCore.App 8.0.15 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.WindowsDesktop.App 6.0.26 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
Microsoft.WindowsDesktop.App 8.0.15 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]

Other architectures found:
x86 [C:\Program Files (x86)\dotnet]
registered at [HKLM\SOFTWARE\dotnet\Setup\InstalledVersions\x86\InstallLocation]

Environment variables:
Not set

global.json file:
Not found

Learn more:
https://aka.ms/dotnet/info

Download .NET:
https://aka.ms/dotnet/download

2025-05-12 21:44:58.999 [info] Project system initialization finished. 0 project(s) are loaded, and 1 failed to load.```

quartz folio
#

Or you haven't restarted after installing it

pulsar belfry
quartz folio
#

If you just installed the .NET SDK then you will need to log out and back in to have it added to your PATH variables

pulsar belfry
#

log out of what?

#

vs or unity

quartz folio
#

Your computer

pulsar belfry
#

oh ok

#

so just lock and log back in?

quartz folio
#

Just restart, it'll achieve the same thing

pulsar belfry
#

ok

#

ok i restarted still getting the same error ``` 2025-05-12 22:17:30.466 [info] No .NET SDKs were found.

Download a .NET SDK:
https://aka.ms/dotnet/download

Learn about SDK resolution:
https://aka.ms/dotnet/sdk-not-found

2025-05-12 22:17:30.468 [info] Additional information of .NET SDKs for diagnostic
Host:
Version: 8.0.15
Architecture: x64
Commit: 50c4cb9fc3
RID: win-x64

.NET SDKs installed:
No SDKs were found.

.NET runtimes installed:
Microsoft.NETCore.App 6.0.26 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.NETCore.App 8.0.15 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.WindowsDesktop.App 6.0.26 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
Microsoft.WindowsDesktop.App 8.0.15 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]

Other architectures found:
x86 [C:\Program Files (x86)\dotnet]
registered at [HKLM\SOFTWARE\dotnet\Setup\InstalledVersions\x86\InstallLocation]

Environment variables:
Not set

global.json file:
Not found

Learn more:
https://aka.ms/dotnet/info

Download .NET:
https://aka.ms/dotnet/download

2025-05-12 22:17:30.480 [info] Project system initialization finished. 0 project(s) are loaded, and 1 failed to load.

quartz folio
#

It says you have no .NET SDK installed

pulsar belfry
#

i installed it

#

opened the exe let it ran ect...

#

before i ran the download. it didn't show this part in the error ```.NET runtimes installed:
Microsoft.NETCore.App 6.0.26 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.NETCore.App 8.0.15 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.WindowsDesktop.App 6.0.26 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
Microsoft.WindowsDesktop.App 8.0.15 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]

Other architectures found:
x86 [C:\Program Files (x86)\dotnet]
registered at [HKLM\SOFTWARE\dotnet\Setup\InstalledVersions\x86\InstallLocation]```

quartz folio
#

You are using x64, so maybe you need to install that instead

pulsar belfry
#

ok its fixed now

quartz folio
#

Now, where have you defined the Collectable type?

pulsar belfry
#
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Inventory
{
    [System.Serializable]
    public class Slot
    {
        public CollectableType type;
        public int count;
        public int maxAllowed;

        public Sprite icon;

        public Slot()
        {
            type = CollectableType.NONE;
            count = 0;
            maxAllowed = 99;
        }

        public bool CanAddItem()
        {
            return count < maxAllowed;
        }

        public void AddItem(Collectable item)
        {
            this.type = item.type;
            this.icon = item.icon;
            count++;
        }
    }

    public List<Slot> slots = new List<Slot>();

    public Inventory(int numSlots)
    {
        for (int i = 0; i < numSlots; i++)
        {
            Slot slot = new Slot();
            slots.Add(slot);
        }
    }

    public void Add(Collectable item)
    {
        foreach (Slot slot in slots)
        {
            if (slot.type == item.type && slot.CanAddItem())
            {
                slot.AddItem(item);
                return;
            }
        }

        foreach (Slot slot in slots)
        {
            if (slot.type == CollectableType.NONE)
            {
                slot.AddItem(item );
                return;
            }
        }
    }
}``` this is the inv code
leaden ice
#

but where is Collectable defined?

pulsar belfry
#

then Collectable cs ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Collectables : MonoBehaviour
{
public CollectableType type;
public Sprite icon;
//player walks into collectable
private void OnTriggerEnter2D(Collider2D collision)
{
Player player = collision.GetComponent<Player>();

    if(player)
    {
        //add collectable to player
        player.inventory.Add(this);
        //delete collectable from the screen
        Destroy(this.gameObject);
    }
}

}

public enum CollectableType
{
NONE, WHEST_SEEDS
}

leaden ice
#

that's Collectables

#

I assume that's a typo then?

pulsar belfry
#

ah so the s messed it up then

pulsar belfry
#

ok so i can pick up the item but its not showing in my inv ui but it shows i have the item

#

no errors in vs ``` using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Inventory_UI : MonoBehaviour
{
public GameObject inventoryPanel;
public Player player;
public List<Slot_UI> slots = new List<Slot_UI>();

void Update()
{
    if (Input.GetKeyDown(KeyCode.Tab))
    {
        ToggleInventory();
    }    
}

public void ToggleInventory()
{
    if (!inventoryPanel.activeSelf)
    {
        inventoryPanel.SetActive(true);
        Setup();
    }
    else
    { 
        inventoryPanel.SetActive(false);
    }
}

void Setup()
{
    if (slots.Count == player.inventory.slots.Count)
    {
        for (int i = 0; i < slots.Count; i++)
        {
            if (player.inventory.slots[i].type != CollectableType.NONE)
            {
                slots[i].SetItem(player.inventory.slots[i]);
            }
            else
            {
                slots[i].SetEmpty();
            }
        }
    }
}

}

leaden ice
#

The error is indicating line 34

#

which line is 34

#

Is it this one?
if (player.inventory.slots[i].type != CollectableType.NONE)?

pulsar belfry
#

if (slots.Count == player.inventory.slots.Count)

leaden ice
#

It also seems like you haven't assigned the player variable here

#

So yeah that would explain the error

#

you're trying to access player.inventory but player is null

pulsar belfry
#

ah ok

#

no more error but its still not showing in the ui i watched the video 4 times still dont see anything wrong the player none is what they have selective and it works for them

cosmic rain
#

Did you do any debugging?

small jetty
#

when do I know to use .normalized?

cosmic rain
small jetty
cosmic rain
#

You need to understand the basics of vector math for gamedev.

small jetty
#

ive been trying recently its been a struggle but ill understand it eventually

cosmic rain
#

It's not that hard. It's something pretty simple among the things that you learn at school.

chrome sage
small jetty
narrow yew
#

how would i go about despawning my prefab

#

called attack

small jetty
#

thanks gang I love usopp

small jetty
narrow yew
#

itl destroy the prefab itself

lean sail
narrow yew
small jetty
#

I’m probabaky wrong 💔💔 but wouldn’t the name of your prefab be the variable you used to instantiate it

lean sail
# narrow yew how do i know what name my prefab is though

What do you mean? You dont need the name of the prefab. You already have a public GameObject attack. You drag and drop the reference into inspector.
Spawn the object, and take the return value from instantiate. That's the in scene object

silent bolt
narrow yew
#

yeah i realized that i was trying to delete it from where i would shoot the bullet

#

and not the bullet itself

#

confused myself

silent bolt
#

😄

narrow yew
#

my fault for the naming being confusing

tawdry skiff
#

Guys, not really for help but more tips... I'm on a project that can be edited by multiples users in the future, how can i avoid this mass of referenced GO ? I know its ugly but this is the error-proof method I found (using child index and names can f-ck everything if someone (or I) change single one of them)

#

(btw I know the [SerializeField] public does the same in the editor but a bad habit from my part)

vestal arch
night harness
#

^ but also in general that doesn't look too awful of a setup

#

like at some point any solution is going to be prone to someone sticking a fork in it

tawdry skiff
#

not necessarily, this is just to display few UI Menu to enable/disable buttons with actions

UI_A3.SetActive(true);
UI_Top_Text.GetComponent<TextMeshProUGUI>().text = ref_ui_a3.GetLocalizedString();
UI_Bot_Back.GetComponent<Button>().onClick.AddListener(() => StartCoroutine(HandleLongPress()));
UI_Bot_DynamicPos.SetActive(false);
UI_Bot_StaticPos.SetActive(false);

So yeah, i guess i'll just to split the whole thing into a MenuUIManager.cs

steady bobcat
#

why are they GameObject fields and not Button or TextMeshProUGUI 😐

tawdry skiff
steady bobcat
tawdry skiff
steady bobcat
#

i do not understand what that means

tawdry skiff
#

let me send a screenshoy

steady bobcat
#

you named something Top_Text yet do GetComponent to get the text...

#

no i dont need a screenshot

tawdry skiff
#

oh you right for that one

steady bobcat
#

If you have 1 gameobject with many objects (bad idea for ui things anyway) you should have a new script to handle them all

kind river
#

I'm making a 2d isometric board game. Most of the time the player move tile to tile. But during some parts, I want to be able to move freely using wasd. I'm not sure how to handle collision with empty tile (that act as wall). I don't know much how rigidbody work. I feel like that's would be the cleanest way to go. Should I investigate this or stick to a handmade approach ?

cosmic rain
kind river
#

I already have the first one working. My question was rather how the later would do with physics. I never worked much with it, I know it is meant for plateform game so I have no idea if it would suit my need

ocean hollow
#

What could be causing this to not work properly? When this script is enabled, i can see the value of the color changing as expected in the inspector, but it doesn't appear to look any on the object different during runtime. It just stays the same color.

However, if I change the color value manually, via the color picker, from the inspector during runtime, it looks and behaves normally


[RequireComponent(typeof(Outline))]
public class OutlineColorCycler : MonoBehaviour
{
    [SerializeField] private float colorCycleSpeed = 1f;

    private Outline outline;
    private float hue;

    private void Awake()
    {
        outline = GetComponent<Outline>();
    }

    private void Update()
    {
        hue += Time.deltaTime * colorCycleSpeed;
        if (hue > 1f) hue -= 1f;

        Color color = Color.HSVToRGB(hue, 1f, 1f);

        outline.outlineColor = color;
    }
}
cosmic rain
cosmic rain
ocean hollow
#

never mind, i realized that i was only updating its value in OnValidate... 🤦‍♂️

fiery steeple
#

Hey, I have an error saying that MyDailyRoutineManager script is null, so I suspect a racing / race condition, how to solve it please ?

steady bobcat
#

Unity is single threaded

somber nacelle
#

Awake and OnEnable are called in pairs, so there is no guarantee that one object's Awake has been called before another object's OnEnable, what is likely happening is that your singleton has not yet had its Awake method called so it's instance property is still null. it's typical to not access a singleton until Start at the earliest to ensure it has awoken

fiery steeple
#

So I should subscribe to the event in Start() instead of Enable() ? 🤔

somber nacelle
#

and if these objects are both in the scene at edit time, you're better off using a direct reference set in the inspector rather than relying on accessing it via the singleton pattern

fiery steeple
#

What if I go through my GameManager ? As all the references are centralized there 🙂

somber nacelle
#

it honestly sounds like you have a spaghetti nightmare on your hands then

fiery steeple
#

why ?

somber nacelle
#

everything relies on everything else and there's a single object with a massive load of references to everything else? this is going to be a nightmare to maintain.

fiery steeple
#

argh 😦

#

I hate game dev

#

I thought I solved the issue of Singletons as I talked with alot of people if it's a good idea or not, I had polar opposite opinions, asked what to do because it's not helpful, then some said pick something and stick to it and Singletons in Game Dev / Unity is fine, then now you're saying it will be a mess 😦

somber nacelle
#

singletons are fine, provided you use them properly and aren't relying solely on them which it seems is what you are doing

#

also if they are singletons then why can't those events be static?

cobalt flint
#

Not entirely sure how you're setting up the overall heirarchy, but you might better off putting it in first scene's heirarchy instead of building it at run time.

fiery steeple
somber nacelle
#

not using them for every single thing for one

cobalt flint
#

Whatever the script is attached to.

vestal arch
#

singletons are for centralized, singular systems
if you have a ton of singletons, maybe you have too many monolithic centralized systems

fiery steeple
#

Here's my GameManager

cobalt flint
#

Whatever the Null script is attached to should just be in the scene. That way the script will be enabled before everything else

fiery steeple
somber nacelle
#

i explained why that is happening already

steady bobcat
#

What is going on here 🤨

fiery steeple
steady bobcat
#

DayNightCycle could be an auto property in its current state and wont it be confusing having 2 collections with nearly the same name?

fiery steeple
cobalt flint
#

Well if it's public it already has setters and getters.

#

Just by calling the object.

somber nacelle
steady bobcat
somber nacelle
#

i already told you that you should just be using a direct reference.

fiery steeple
somber nacelle
#

you can still do that? there is nothing stopping you from accessing that static property

fiery steeple
somber nacelle
#

why did you change that line? you weren't accessing the static property through its Instance property anyway

fiery steeple
#

I guess I can't make OnEnable() static otherwise it wouldn't make sense

somber nacelle
#

but this does also seem like an abuse of static anyway

fiery steeple
# somber nacelle why would you?

because it's not a "static context", so to make it static I have to make OnEnable() static but it wouldn't make sense in this case

somber nacelle
#

why would you need a static context for this?

fiery steeple
#

That's what the error say

somber nacelle
#

do you just not understand wtf static is or what your code was even doing?

fiery steeple
#

I understood what my code was doing but right now not using the class directly and use a direct ref confuses me

somber nacelle
#

look at the difference here and apply the same logic to your new code

vestal arch
#

the non-static context in question is dailyRoutineManager.

somber nacelle
fiery steeple
vestal arch
#

so why'd you change the OnEnable lol

fiery steeple
somber nacelle
#

the whole point of the direct reference was to not be using the Instance property which was null at this point

vestal arch
#

yeah because Instance is a static member and dailyRoutineManager is an instance, not a static context

fiery steeple
somber nacelle
#

again, this is a clear misunderstanding of what static is and does and perhaps you should go review that

fiery steeple
#

static makes the member or the method belong to the class rather than the instance itself

vestal arch
#

yeah, and now you're trying to access a static member from an instance rather than the class

vestal arch
#

DailyRoutineManager.Instance is an instance of DailyRoutineManager, but you already have an instance right there, dailyRoutineManager

fiery steeple
#

Do I do the same thing with DayNightCycle just to be sure ?

#

Also using a direct ref here isn't that a bad practice because it's coupling those classes together ? I remember hearing that somewhere 🤔

somber nacelle
#

you were already coupling them together, this is just more directly referencing the desired object

#

nothing about the actual logic here is changing, just whether you have a direct reference or are relying on the static reference via the singleton pattern

fiery steeple
#

so what's the best way to avoid coupling (if there's any) ?

somber nacelle
#

with how spaghettified your references are, it doesn't seem like there is a way for you to decouple it at this point as it would pretty much require a complete rewrite since you are currently relying on specific kinds of objects

fiery steeple
#

I'm still at the start of the project, so I can afford myself rewriting the code

#

but I don't know what's the solution

somber nacelle
#

you'd have to look into different design patterns and things like dependency injection if you want to completely decouple your classes from each other

steady bobcat
#

You can control your initalization flow manually and give dependencies to instances as needed, you dont have to use a DI framework

#

Either way, not relying on static references will improve things

fiery steeple
#

but wouldn't DI cause the same issue as you need to pass a reference as a parameter, what if that ref isn't loaded yet making it null ?

steady bobcat
#

Well you do it in a smart order duh

#

e.g. Init object A, load object B, init object B with ref of A.

fiery steeple
#

I don't understand 🤔

fiery steeple
steady bobcat
#

well i somehow have managed doing this over many years

#

as long as you dont design things where 5 components need to all reference eachother then it works out

fiery steeple
safe flame
#

Well yea you do plan it piece by piece, but you don't start a new notepad every time you plan something new for the project

#

You add it to your current notepad or whatever you're taking notes in

fiery steeple
#

yeah

safe flame
#

And yea it is difficult, software architecture is a whole field that people study for

fiery steeple
#

also, isn't DI a one way route, meaning that you can only send the injection but not retrieve it directly ? (I don't know if it makes sense the way I say it 😬 )

somber nacelle
#

yes, that's part of the point of decoupling the objects

fiery steeple
somber nacelle
#

huh?

lean sail
fiery steeple
#

@somber nacelle
Let's say I have :

  • Class A : calling Class B method and passing the injection
  • Class B : declare the method that will receive the injection

If i create a new class (let's call it Class C) that needs that injection, I need to go back to Class A to add Class C method and send the injection.

It feels weird as I'm used to events where you do the declaration of the event in Class A, then you don't touch it anymore, all the future classes needing that event have just to subscribe that event. So Class B ask for a subscription from A (so I have nothing to write in Class A for that, but I have to do the subscription in Class B)

somber nacelle
#

can you explain what you mean by that first part?

fiery steeple
somber nacelle
#

yes

fiery steeple
#

Let me write an example

somber nacelle
#

sure, but it sounds like you aren't quite understanding the purpose of dependency injection

#

it's also not the only thing you need to do to decouple the classes, just part of it.

fiery steeple
fiery steeple
# somber nacelle it's also not the *only* thing you need to do to decouple the classes, just part...

Well by starting writing my example i got stuck and made me have a question about refs again. In this case I want to call a method of class B inside the Send() method of class A and passing player as the injection but realized that I don't have a ref to class B, meaning that I'm back to the same ref coupling that we had before, meaning that I'm missing something in the understanding of DI 🤔

From that problem, my logic tells me that it's not just class A doing the DI like that out of nowhere to send it to class B and that class B needs to ask class A for that and passing itself (class B) as a parameter on that call for class A to be able to send back a response to class B with that player DI.

somber nacelle
#

unrelated to the content of your post, but why the fuck would you send a screenshot of your code in the discord text window instead of just putting it at the end of your text? that makes 0 sense, and screenshots of code are discouraged here so it makes even less sense to do that with that context

fiery steeple
#

my bad, I started writing it first on discord then I realised the issue with player ref, then copied that code on sublime text to not loose it then write the message and also because I modified my code so that's why

#

but here's the code :

public class ClassA {
  private Player player;

  public void Send()
  {
    
  }
}```
somber nacelle
#

anyway, you have your thought process backwards. if class A needs to call a method on Class B, then Class B should be injected into Class A, not Class A injected to Class B.

#

the only reason it would make sense to inject Class A into Class B in that case would be if you were subscribing to an event on Class A from Class B, then Class A doesn't need to know anything at all about Class B

fiery steeple
somber nacelle
#

that's not the opposite, that's something else. if Class B needs to know about Player but not about Class A then player should be injected into both

fiery steeple
#

I got this, so it solved my issue of ClassB ref

public class ClassA {
  private Player player;

  public void Send(Class sender)
  {
    sender.Receive(player);
  }
}

public class ClassB : MonoBehaviour {

  void Start() {
    ClassA classA = new ClassA();
    classA.Send(this);
  }

  public void Receive(Player player) {
    print($"I received {player}")
  }
}
somber nacelle
#

that is the opposite of decoupling lmao

fiery steeple
#

of course here let's say Class B inherits from Class

#

damn it

naive swallow
#

When you have two objects that reference each other that's a telltale sign you're heading straight into spaghetti town

fiery steeple
naive swallow
fiery steeple
somber nacelle
#

also ClassB constructs ClassA

fiery steeple
#

damn it, should I make the ClassA static to avoid constructing it ?

somber nacelle
#

if ClassB needs the Player object but it also constructs ClassA, why doesn't ClassB just construct the Player object?

fiery steeple
#

makes sense

naive swallow
somber nacelle
#

what is the actual point of ClassA here? this is why vague approximations of what you need are bad because it's wrong on so many levels and has literally no bearing at all on what you are actually trying to accomplish

fiery steeple
#

@somber nacelle @naive swallow Could you rewrite my code the proper way please ? So I can see what's the proper way of doing 🙂

naive swallow
fiery steeple
#

Because that's what I do for example in my DayNightCycle but didn't know that was called DI 🤔

naive swallow
#

If you have a class that holds data and you want to push that data out to listeners that's what events are for

fiery steeple
#

so does that mean that DI is always done through events ?

#

*through an event

naive swallow
#

DI isn't like, a single action. It's just the idea of having all your references there ahead of time

#

It's a paradigm, not a syntactic thing

fiery steeple
#

Alright, but could it be done without events ?

late lion
#

I would rewrite it, but I don't understand what you're trying to accomplish.

somber nacelle
#

this all came about because they wanted to decouple their code and part of the suggestion for that was dependency injection

#

of course the issue they were originally experiencing that lead to them wanting to decouple had a few solutions provided to them so they don't need to worry about all this

hoary yoke
#

hey! anyone got a minute?

hoary yoke
#

aw man 🥀 well anyways: I'm trying to restrict the area in which my 2d character can move around but it just wont work... any suggestions?

vestal arch
#

how exactly doesn't it work?

#

ah

#

wait

#

look at your condition closely

hoary yoke
#

yep ive got it now haha

#

thanks

rigid island
jagged belfry
#

I want to make a combat system using a third person controller on my character and I'm using the player controller script for that, I've put an event on the attack animation so that when it reaches the impact frame a function is activated and it removes damage from the enemy, I don't know if this way is the cleanest or there's a better way to do it

#

Maybe using a box collider on my character's hand is a better option., or idk

cobalt flint
swift falcon
#
//Somewhere else
RaycastHit hit;
if (Physics.Raycast(cam.transform.position, cam.transform.forward, out hit, maxDistance: rayMaxDistance))
  PaintTextureCoord(hit.textureCoord, renderer.material);

public void PaintTextureCoord(Vector2 textureCoord, Material material)
{
    Texture2D paintTexture = material.mainTexture as Texture2D;
    if (paintTexture == null || !paintTexture.isReadable)
    {
        Debug.LogError("Paint face material needs a Read/Write-enabled Texture2D.");
        return;
    }

    Debug.Log("Texture coordinates: (" + textureCoord.x + ", " + textureCoord.y + "), Width: " + paintTexture.width + ", " + "Height: " + paintTexture.height);
}

Why would the texture coordinates be 0,0?

#

My object is basically a stretched cube split into 2 gameobjects. One of them is the top face, and the other is the rest of the faces
I'm currently selecting the top face in blender and i'm pretty sure the uv coordinates stretch throughout the [0,1] range

#

I already set read/write to enabled, compression to none and format to rgba32 bit

#

Solved: collider was set to convex -> raycast didn't receive textureCoord info

warm mango
#

Is there a trick to getting [InitializeOnLoad] to work?

#

I've added it to my script, as well as using UnityEngine and none of my debug logs are appearing like they do when I hit the play button

somber nacelle
#

just to confirm, you are using this for editor code, right? because that's the editor version, RuntimeInitializeOnLoad is the version for runtime

#

and it's on a static constructor, not a method? because InitializeOnLoadMethod is a separate attribute

warm mango
somber nacelle
#

yes, because InitializeOnLoad is for static constructors for editor-related classes. as i pointed out there is a separate attribute for Runtime, and for each there are separate attributes for methods rather than constructors

warm mango
#

I was hoping it would run while I'm in the editor so I don't have to hit play each time and wait for the whole thing to compile

I'll give the method a shot because I don't believe this is a static constructor

somber nacelle
#

I was hoping it would run while I'm in the editor so I don't have to hit play each time and wait for the whole thing to compile
hoping what would run? if this is some component's Update method (or other unity message) then you're using the wrong attribute entirely, you would want to mark the class with the ExecuteInEditMode attribute for that

warm mango
deft thicket
#

Ok I've followed a tutorial on making a cannon but its not functioning as it should and I don't know what isn't working as it should anyone know what went wrong?

cosmic rain
deft thicket
#

oh right mb

#

one moment

cosmic rain
#

If you can't explain in words, record a video

deft thicket
#

that is what ill do

#

It’s like it snaps to the bottom right and doesn’t have much range of movement

quartz folio
#

The tutorial you followed looks like it's designed for 2d

#

In fact, it looks like it's poorly designed for 2D

deft thicket
#

Ok dang any way of making it work or should i look for a new one

quartz folio
#

At no point is the mouse position converted to world space

leaden ice
#

It seems to be mixing up world space and viewport space positions/directions

deft thicket
#

Oki hm any recommendations for a cannon tutorial or guide that will work in 3D

brave geyser
#

That is a very specific need. Maybe look for help on pointer following logic in 3D? Try to find more generic help and adapt it to your use case.

silent bolt
young yacht
#
int secondEnemyChance = UnityEngine.Random.Range(1, 2);
                int randomPoint = UnityEngine.Random.Range(0, generalSpawnPoints.Count);

                GameObject spawnPreview = SpawnEnemyPreview(generalSpawnPoints[randomPoint].transform);

                yield return new WaitForSeconds(0.6f);
            
                GameObject enemy = Instantiate(currentFaction.enemies[0], generalSpawnPoints[randomPoint].transform.position, Quaternion.identity);
                Enemy enemyScript = enemy.GetComponent<Enemy>();
                enemyScript.playerController = playerController;
                enemiesSpawnedList.Add(enemy);

                Destroy(spawnPreview);

does anyone know why the enemy doesnt spawn on the spawnPreview spot?

#

fixed

normal niche
#

hello, i was wondering how i would go about making a hand wrap around objects of dynamic sizes and shapes in unity, i mostly need hints but code examples and vidoes/websites would be good too, thanks in advance 😁

#

i have a rigged skeleton with 3 points for each skeleton in each finger, thats probably interesting but i want to avoid clipping of hands into objects as much as possible 🤔

young yacht
#

or use IK

normal niche
#

how would i go about doing it with IK as that is what im using for other related issues at the moment, would i predefine 5 points on each item and then wrap the fingers to those positions?

young yacht
#

yea

#

exactly that

#

its a lot of work if you have a lot of weapons

normal niche
#

okey, cool, ill give it a try, it just seemed like the most logical ease of use solution

signal vale
#

So, question, Does this:

if (CanDrive)

Mean if the bool CanDrive = true then itle allow the code to run?

normal niche
#

not a lot of items so i think ill manage, thanks for the help!

signal vale
#

Cause I'm running into Alot of issues with the my code haha

young yacht
#

depends on what you want to do with that bool

signal vale
#

I have a boat that I'm trying to get to move, and Upon pressing "F" whilst in the collider it sets the Bool to "True" allowing WASD to move the boat, and also dissabled my characters movement script, but seems to not be working.

#

oh wait

#

its on ENter

#

not stay..

#

lmfao

young yacht
#

guess that solves it

#

also so you know

signal vale
#

Oh wait,

young yacht
#

you might want to put those inputs in Update() or FixedUpdate()

#

otherwise they wont run

#

it'll only check for a frame when the function OnTriggerEnter triggers

signal vale
#

Yeah,

#

I changed it because I had some previose code that was using Update, but I couldn't call two different "Void Update()" so I tried to make one on Trigger, Proberbly could've made a Bool, for OntriggerEnter / Exit does ""

young yacht
#

OnTriggerEnter() you set canDrive = true

#

then in Update()

#

if (canDrive) -> do whatever you want here

signal vale
#

Yeah, only issue being the boat will continue to move, maybe my code needs a revision? because using all these triggers is causing issues,

#

Such as my camera not activating with each button press of "F" sometimes it takes a few times

night harness
signal vale
#

1second,

#

thats the newest remedition

night harness
#

why are there extra brackets and extra indentation in ontriggerstay

signal vale
#

Because I'm a noobie, and don't knnow how to properly indent 😦

#

does extra brackets mean something bad?

night harness
young yacht
night harness
#

theres no condition here

young yacht
#

why not use Unity's New Input System?

night harness
signal vale
#

Because my college course has us set on unity 2022

night harness
#

unity 2022 has it

young yacht
#

ah i see

signal vale
#

Eitherway, I don't plan on using it, as I need to learn to code.

young yacht
#

you're still coding while using it

night harness
#

is your ide configured properly

#

there are a couple things wrong with this that shouldn't let you compile

young yacht
#

biggest difference it makes is its easier to plug multiple devices

#

such as gamepads, keyboards, steam deck...

#

and makes your code cleaner

signal vale
#

not make a triple A game HAHA

young yacht
#

of course

#

anyways that OnTriggerStay() looks messy asf

night harness
#

whats the command for ide setup

#

anyone know

#

oh just

#

!ide

tawny elkBOT
signal vale
night harness
#

there's code-breaking errors in that script that your programming program should be tellling you about

#

if its not it's not setup correctly

signal vale
#

I'm using visual studio, and no, its not telling me. shows autofills

#

saying that, I'm still stuck on visual studio 2022

#

might be wise upgrading

night harness
#

thats more than enough

signal vale
#

By autofills i mean only previouse things I typed

night harness
#

ah apologies, one of the mistakes was removed in your revision and apparently you can just add random brackets to places

#

did not know that

#

you should debug what tag the collider coming into ontriggerstay is

signal vale
#

I forgot I Removed player

#

woops

#

let me add the if statement back

#

wait

#

should it matter? as the movement of the boat goes by the bool, not if player tag is in collider,

night harness
#

look where that bool is set to true

#

look what needs to happen for that to happen

signal vale
#

Needs to be in the collider attached to the object, the object with the tag "Player" needs to be in the collider, and F needs to be pressed,

#

shouldnt "F" go before player tag?

#

Don't think it would matter to much

night harness
#

doesnt matter yeah

#

so you need to debug

signal vale
#

Well i have boat movement,

night harness
#

does something enter the trigger? is that something tagged as the player? is f being pressed? etc.

signal vale
#

gotcha

#

Seems to be working now, as its setting the bool to true.

#

only if im int he collider#

night harness
#

if it works it works 😄

#

but yeah use debugging to narrow down what your problem actually is

signal vale
#

Trying to dissable my player movement script now lmfao

#

forgot how I did that

#

Figured it out 😛

#

How would i do

get gameobject"" if script = enabled do ""

#

This should work.... " if (myScript != null && myScript.enabled)"

vestal arch
#

code formatting is backticks, `, not quotes

normal niche
#

quick question, are targets for animation rigging IK Constraints prebaked or can they be changed at runtime, i dont know if my question makes sense but i think it does?

young yacht
#

i mean they can

#

but you'd have to bake them again through code

#

i had the same problem

#

what i did instead was just move the target itself to where you want it to go

#

instead of setting a new target

#

for me was moving the character's head

normal niche
#

that makes so much more sense, silly i didnt think of that haha

young yacht
#

ifkr lmao

#

took me forever

#

to realize that

normal niche
#

im moving the fingers to make a grasp animation of sorts

#

thanks, that makes a lot of sense

sharp garden
#

anyone with spline experience?

in my script I need to get the interpolation ratio (so a float from 0 to 1 representing the percentage of the whole spline) that's closest to a given Vector3.

I've been using SplineUtility.GetNearestPoint to get all the nearest point info, but the documentation is really confusing for the 4th out argument:
The normalized interpolation ratio corresponding to the nearest point.
I don't really know what this means - it's clearly not the normalised interpolation ratio for the whole spline, it's 'according to the nearest point' but I have no idea what that is in this context lol.

I assumed it was the interpolation ratio for the current Curve (i.e. the spline segment between two knots) but this doesn't seem to be right either since if I add this out value to the current curve index and do float normalisedPos = SplineUtility.CurveToSplineT(railSpline, curveIndex + normalisedCurvePos); , CurveToSplineT returns an unexpected value that doesn't correctly represent the nearest interpolation ratio on the spline.

super lost lol, any help would be appreciated, especially if anyone knows an easier way to get the interpolation ratio of a whole spline nearest to a vector3 🙏

night harness
#

whats the answer from

sharp garden
#

chatgpt is no help for this

somber nacelle
sharp garden
#

SplineUtility.GetNearestPoint(spline, position, out int curveIndex, out float curveT);
this is literally a chatGPT hallucination 😭 there is no out int curveIndex from that function

night harness
#

Yeah but it sure looked pretty right !

#

that's what matters 😅

sharp garden
#

did you read my question in full?

#

it doesn't return the normalised position for the whole spline, only corresponding to the nearest point. (not totally sure what that means)

steady bobcat
#

What I have done before:

float3 nearest;
            float t;
            SplineUtility.GetNearestPoint(SplineContainer.Spline, SplineContainer.transform.InverseTransformPoint(transform.position), out nearest, out t);
            dragPos = SplineContainer.transform.TransformPoint(nearest);
            transform.position = dragPos;
#

I picked the wrong function above so sorry about that

#

t is the normalised position (0 to 1) for the spline position nearest

sharp garden
#

that's pretty much what I'm doing atm

#

it works for splines with only 1 curve, but if they have 2 or more it produces results that are too high (i.e. close to 0.8) towards the center of the spline

#

this (yellow sphere is the given vector3) produced 0.8334275 even though it is in the middle and should be closer to 0.5 or 0.6

vagrant blade
#

You're logging t?

steady bobcat
#

I've only used it with things with 1 spline but 3/4 knots

sharp garden
steady bobcat
sharp garden
#

yes

steady bobcat
#

are you sure you are transforming the position correctly like in my example?

#

to spline local, then back after

sharp garden
#

yeah, this is argument 2 Vector3 localSplinePoint = Container.transform.InverseTransformPoint(playerPosition);

#

I'll drop my whole code here

#
public Tuple<Vector3, float> FindAnchorPoint(Vector3 playerPosition)
        {
            //Convert player pos to spline local coordinates
            Vector3 localSplinePoint = Container.transform.InverseTransformPoint(playerPosition);

            //Spline, float3 input, float3 output, normalisedposition, resolution, iterations
            SplineUtility.GetNearestPoint(railSpline, localSplinePoint, out float3 nearest, out float normalisedCurvePos, 12, 2);

            //Use CurveToSplineT to convert normalisedCurvePos to T value for whole spline (doesn't work lol)
            float normalisedPos = SplineUtility.CurveToSplineT(railSpline, normalisedCurvePos);
            
            //Convert nearest point back to world coordinates
            Vector3 nearestWorldPosition = Container.transform.TransformPoint(nearest);

            return new Tuple<Vector3, float>(nearestWorldPosition, normalisedPos);
        }
#

(I'm going off the assumption that GetNearestPoint is getting the normalised point along the curve, not the whole spline, but I don't think that's right either since the results are off when I use that to call CurveToSplineT as well)

night jetty
#

anyone know how to make a world space canvas not get affected by fov change while still not having different scaling depending on the screen size im kinda stupid

brave geyser
night jetty
night jetty
leaden ice
brave geyser
#

I thought maybe your world-space UI was a health bar over an enemy or a "!". Those can often work as overlay elements, they just move around on the canvas to match placement in the world.

But if you are looking for post-processing on the UI, then I'm not sure what is best there.

night jetty
leaden ice
night jetty
night jetty
night jetty
leaden ice
night jetty
leaden ice
#

no I mean you said it is affected by fov

#

I want to know in what way

night jetty
leaden ice
#

A screenshot would be nice

night jetty
brave geyser
#

So this is like a player stat (health?) and not something that needs to be in-world for some reason?

leaden ice
#

basically ideally yhe UI would be rendered on a separate camera whose POV doesn't change but with camera stacking yes the PP on the highest layer camera basically applies to the full composited image from all the cameras

#

so it's quite a pickle 🤔

night jetty
night jetty
naive swallow
#

Is there a way to change the "Sample distance" of the float array passed to TerrainData.SetHeights? I have the terrain at the size I want (let's say 5000x5000) and a float array with some smaller number of points (say 1000x1000). Right now, it's setting the height of a corner of the terrain to what I have in there assuming the indices are 1 world unit apart. Instead, I want those indices to be "fractions of width" instead of "real space units". Like, heights[0,0] spans an area of 5x5 in real space, instead of 1x1, since the width of the terrain is 5 times the length of the array.

modern epoch
#

i need assistance now

#

i have 2 pathfinder grids

#

2 pathfinder graphs*

#

but the second one isnt working

#

what do i do to activate it

naive swallow
#

Finish a sentence, then hit enter

modern epoch
#

anyone? my time is running out

silent bloom
#

Hi , iam trying to achive google login in playfabs with unity when i try to take a the gradle build appears which coreLibraryDesugaring configuration contains no dependencies. If you intend to enable core library desugaring, please add dependencies to coreLibraryDesugaring configuration. Can any help me on this

vestal arch
vagrant blade
normal niche
#

I have been stuck for a bit not on how i would keep the hand at its original position without the animation overriding it but i keep getting wonky results, how would i go about doing this? I'm using unity animation rigging (sorry for the bad quality, idk why that happened)

#

I thought of using a Two Bone IK Constraint to keep the hand still but it keeps bending the arm in weird ways and messes with the position of the hand, i need the position of the hand to not change from its original position 🤔

leaden ice
#

It's not clear what you mean by keeping the hand at its "original position"

normal niche
#

the start position from frame 0 for the idle pose in my animator, hope that makes sense

#

at the moment, the flashlight moves with the animation, i want the hand to be kept in place, not affected by how the arm/hand moves with the animation

leaden ice
#

But yeah IK most likely

normal niche
#

aight, ill give it a shot ty (nvm, fixed it)

rigid island
#

Anyone know how do I fix this ?
Even though its underlining red its not compile error, Ignoring seems fine but its hella annoying to look at lol

The dlls In my Plugins folder were extracted from project published with dotnet 2.0 standard so not sure where its getting .net 9.0 from

#

Ohh its the dlls in my StreamingAssets folder

steady bobcat