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
#archived-code-general
1 messages · Page 448 of 1
yes absolutely
use something like if (Vector2.Angle(Vector3.up, normal) < 3)
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?
The data is strings..?
"string array"?
For BPM/beat detection people usually use FFTs.
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)
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.
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.
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
you're setting the vertical velocity to 0 there pretty explicitly
ohhh
no clue why i named it that
if i remove the 0 there the Input.GetAxis("Vertical") will in the Y axis and not Z
removing it doesn't make sense
replace it
with what?
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
like this?
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
They renamed it in Unity 6
oh alr
do i need to make my own gravity script if i want to change the gravity in 3d?
It depends what you mean by "change the gravity"
you can set it to whatever you want in physics settings without any script
when i added this my player just flew out of the map in Y axis and the game screen became blue
you would need to show the exact code you used
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.
alright
(and there' no reason to have this long-lived position vector)
lol alr
i meant float array. I do not know why I said string
sorry about that
so the data is an array of five floats that change with the average energy of some spectrums of an audiosource
Is there some way I can make the game delete itself in a certain situation in unity?
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
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
thanks man, I’ll check it out
you can follow tutorials
just make sure to understand what theyre doing
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
is it perhaps from a separate instance of the component?
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
it's.. not a singleton though?
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
that's a weird way to write a singleton lol
destroying the old one instead of the new one
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
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);
it isn't supposed to persist over scene changes
this is kinda antithetical to having a singleton
ok, try clicking the log and see what instance it takes you to
Doesnt take me to any instance
did you exit play mode
not yet
turn error pause on or something and do it while still in play mode
oh wait uh
double click it?
opens the code
Based on the code you've shown, you have a zombie. You never unsubscribe from GameManager.Instance.PostGame so when UIManager is destroyed, it sticks around in memory. You've been tricked by the one in the inspector, that one is alive and fine
clicking on the error won't take you anywhere because the UIManager that throws the error no longer exists by that point
definitely what reeper said
that sounds sensible Ill go and unsubscribe xd
also reconsider your design about whether it should actually be a singleton or not
I never heard a singleton needs to be persistent before, only single, hence the name
the "single" in singleton means a single instance exists through the lifetime of the program, not a single instance exists at a time
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
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
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
Yes and? It doesnt know the UI objects that dont exist in the main menu but do exist in the game either
you would have UIManager inform the GameManager of its existance
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
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
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
How will it know of a reference that doesnt exist
it does exist though
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
if a UIManager exists, then its reference also exists...?
Im not talking about the reference to a UImanager
Im talking about the reference to an object that the UIManager accesses
UIManager would be in the same place with the same references
but then we are exactly where I am now
Where I have a UIManager in the menu and one in the game
what would change would be that UIManager doesn't treat itself as a singleton
The one in the menu handles menu UI the one in the game handles game UI
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
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
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
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
The GameManager is
No that one isnt
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?
you can try using OnValidate but otherwise you may need to use OnEnable/OnDisable and [ExecuteAlways] to write the asset name to this var.
!code
Posting code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
anyways, rb.linearVelocity is relative to world space, not local space
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 🤔
Devops is a whole field specializing in improving software development efficiency. For example, with version control.
It can can be used in gamedev just like in any other area of software development.
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.
- 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.
- Break down the development into tasks. Use services like Trello to keep track of tasks and their progress.
- 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.
- 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.
- 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.
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.
Well, planning is just making the high level outline of your systems, so it's sort of what you're doing. Writing down block diagrams(or something similar) on paper demonstrating the components of the systems and how they should interact with each other can be helpful.
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
Oki, will try to transfer my rough system descriptions into diagrams more seriously. Thanks!
If you need help with a specific diagram/system, feel free to provide some more details on it and what you have so far.
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
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.
Honestly imo design patterns are a coding language agnostic thing & common oop design patterns are universal
One still needs to understand which make sense and why in context
yep but that's learned with experience, practicing with them just makes you a better programmer in general
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.
Sure, but some of them are more useful then other given the context/language you use. You won't use pattern that requires considerable amount of performance in a runtime context by example.
100% agree but that comes with practice to know which one to use, I love strategy pattern personally but a strategy doesn't/shouldn't replace a state machine (even tho you could)
regardless the other advice is good, no need to hammer that point
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.
Is this a coding question? If not, consider moving your question to #💻┃unity-talk
Make sure to provide images of the inspector of the splats and scene hierarchy. Is this 3d or 2d?
I spawn them in using a script.
Where I set the transform and other stats
3d
I'll get the screenshots in a sec,
If it's not an issue with code, you should move your question to #💻┃unity-talk (seems unlikely code related)
aight. i'll see
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?
A tool for sharing your source code with the world!
Wait I think I got an idea how to work around it
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
Normally interfaces wouldn't hold any data and simply outline methods to be implemented.
This may have changed though with more modern C# but ideally, you'd have the implementation done elsewhere
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.
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?
mobile is less active because nobody cares to talk about mobile stuff, advertising it here off-topic doesn't change that.
soooo don't talk about mobile stuff, is what you just told me.
i told you that most people here don't care about mobile stuff
ya is what i say
if they do they do so at work and get paid to care 😉
Declare the member with it's specific type.
Or the class needs to be generic
the type can very. I prefer not to make the class generic, but I think I've got no other choice
The type parameter T will have to be defined somewhere. Either when declared as a field or when the enclosing generic class is declared etc.
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
If so, they could probably forgo the generic interface and simply use the concrete super type directly in the interface.
you could put a type constraint on it and it'd work either way
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
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?
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...
//....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
Log the name of the object that was destroyed
Time to learn how to use the debugger in your IDE https://docs.unity3d.com/6000.1/Documentation/Manual/managed-code-debugging.html
some logs may help but using breakpoints with a debugger will let you see exactly what is calling this function and when
I'll give that a shot.
issue is, it's for a game jam. and I don't have too much time to debug this forever :/
I think this wont work for what I need :(
then the other option to keep the same gameobject across scenes is DontDestroyOnLoad()
or static classes
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!
this really just sounds like you want to make the player a prefab, and then spawn it in when desired
And/or use a bootstrap scene and DDOL objects.
Games i work on have about 10-25 langs and we have a main english oriented font and then fallback fonts to cover cyrilic, chinese/japanese, korean and sometimes arabic (maybe one for vietnamese too?)
A good idea is to automate showing all your game text in all langs in a scene to check for problems
Maybe Scene Templates is what you are looking for
https://docs.unity3d.com/Manual/scene-templates.html
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?
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)
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?
yea the non english fonts are set to dynamic and on game start I add the lang name to the font i specify to prevent lag later.
https://docs.unity3d.com/Packages/com.unity.textmeshpro@3.0/api/TMPro.TMP_FontAsset.html#TMPro_TMP_FontAsset_TryAddCharacters_System_String_System_Boolean_
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.
Gotcha. Thanks for the help. Guess I'm adding a whole bunch of Noto Sans font fallbacks tomorrow then 😄
would a infinite dungeon game be too advanced for mh second game? my first one was flappy bird and I learnt quite a bit
Could be. It's hard to say just from that info.
oh alright, I decided to work on another project anyways!! it seemed too overwhelming for me
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
Any kind of code in update reduces framerate. The question is how much and whether it's acceptable in the context of your project.
It also depends a lot on what you're doing in the if statements. What does the check involve? Is it a super heavy multidimensional matrix comparison? If so, yes of course that's gonna be heavy. But it's not really the if statement fault.
If you have performance issues, you should use the profiler to investigate them.
Here you go: "help"
everytime i try to program something involving some math it makes zero sense 💔 what should i do
dies
Maybe ask in #📦┃addressables instead.
Learn math.
my years of cheating caught up to me 💔
nothings stopping you from learning it still. there are tons of resources out there on the basics of vector math which is really a majority of what you need to know.
the vector math is mostly what has me caught up but ill go and find some
thank u!
should I send my code? could you check it out?
i don't know what i'm looking for
it is quite long though
it doesnt have to be unity specific either. vector math is usually taught like grade 11/12. Its been awhile since ive ever had to look at basics of vector math, but khan academy was a good resource around my time.
Someone might have a look if you share the !code properly. But to make it simpler on you: no, just the if statements themselves do not make a noticeable impact on performance. Even if there are hundreds or thousands of them.
Posting code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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)
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
Are there cases where events aren't declared as static ?
Depends on the person and context but from what Ive personally seen there usually not static
I saw the opposite 😬
Really depends on the usecase
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 🤔
Heads up that no modding talk on this server if that’s what this is
unless just comparison
no it's not modding, I'm recreating that style of game but in 3D
in Unity
I almost never create static delegates, as they're often a really great way to create a leak
They should never be static imo
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
how ?
If a subscriber fails to unsubscribe then it and everything it references will remain in memory
I have this for that
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
What's that (Event Bus)?
In my case it's a Singleton
To answer your original question though for example if your prisoners has events you may prefer them to exist on each instance
by "has events" you mean if they subscribe to an event or if the event is created in their class ?
I'm really confused when for a single question there are multiple answers 😤
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.
But couldn't that still be made through static events by passing the button itself as a parameter of the event ?
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.
Oh I see, thanks 😄 Now though I don't see a point of making the event not static, do you have an equilvanet for it to show that it's important too ? 🙂
Let's say you want to make a "kill feed" for a shooter game, just a list of "Player A killed Player B" in the corner. For that use case, the script managing the kill feed doesn't care about one specific player, it wants to know all the kill events. Then it would be handy to have a single event that is invoked for whenever any player kills any other player.
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.
But couldn't that be achieved by having the event inside the player class and passing the killer or victim as a parameter ?
Then the kill feed script would need to get a reference to every player as they are created, just to subscribe to their OnKilled event. Versus subscribing to one OnPlayerKilled event in GameManager.
no like not having a kill feed script at all and having the event directly in the player who did the kill or is killed
What script is managing the kill feed then? The player script?
depends what will be inside that Kill Feed script
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.
but once notified what it does with that ?
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.
So if it's on Player, that means the KillFeed must subscribe to every event of every player ?
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.
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 ? 🙂
hi i have a collision problem do i ask here?
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.
So I should switch that event to not be static ?
It's recommended.
Do you have good resources (mainly youtube if possible) that talks more in depth about everything you taught me please ? 🙂
Not off the top of my head. And I don't have time right now to hunt one down.
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
maybe the character data for those glyphs is bad? you could check the glyph table in the TMP font asset and see if they've got bad advance values etc
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... 🫠
if you paste that same string into other text components, does it render OK?
Good idea, it seems to keep the weird stagger in other elements too - so I assume there is something wrong with the string?
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!
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)
);`
that looks harmless to me, i think it's more likely the problem is in the localization sheet itself
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 ❤️
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.
Can you have multiple pathfinder objects in a scene
My second pathfinder isn't showing an outline
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.
share your !code properly please
Posting code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
so use the backquotes?
Can you have multiple pathfinder objects in a scene
see the "large code blocks" section
oh ok ok.
https://paste.mod.gg/hjbzadldcjkt/0
does this work? i don't know how to use it
A tool for sharing your source code with the world!
ok what was your question?
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
you seem to never reset y?
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
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
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
unity might be able to handle larger values over 32 or 64 bit
uh this doesn't really make sense
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
What about if you walk off an edge
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:
- have an initial right velocity that comes to a complete stop
- 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.
Here's a video of what I have so far because I feel like the explanation wasn't very clear
What setting are you using for the Limit Velocity over Lifetime?
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
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.
is there a way to set the linear velocity of the particles outside of this module?
Yes, start speed in the main module.
Then it will go in whatever direction is dictated by the emission shape.
is there any way for the emission shape to all move towards a certain direction?
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
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.
ah ok, I think that's the closest I'll get. I'll try messing around with the cone shape some more
ty so much for your help!
Then yeah, I guess it never resets, but then again as long as the player is falling it shouldn’t until the player makes contact with something.
Ah, then maybe that isn’t the problem
I’m starting to think I just have a really bad laptop
TIL that there is a difference between comparing objects and variables
...no? you can't compare the variable itself, you compare the value it holds
yeah thats what i meant
there still isn't really a difference
you can using is
that's not comparison
wdym
ok, what do you think the difference is...?
one uses Object.operator and the other use int.operator
that's because of the types of the things you're comparing
yeah, i was saying that i never knew that c# had to specify a difference
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
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)
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
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
Never played it...but you can probably do this with triggers and Additive scene loading
I imagined the trigger approach, what's the additive scene loading bit?
which is more preferred?
up to you..they both do the same thing
Additive scene loading so you can load a seperate part of a level when needed without delays
i know but which is better
there is no "better" if they both do the same thing..
for better code readability
Ohh, thx I'll look into it.
ya its preference I think, personally would be the second one
kk
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
This makes no sense, nothing calls "BreakObject". Are you sure its not just normal gravity affecting it?
also tags are bad long term so try to move to your own components for this data instead
I tried calling Break object within Case “Breakable” but it didn’t help not change anything
Turned gravity off
I see. What’s a better method?
fuel for example can be:
if(collision.gameObject.TryGetComponent(out Fuel fuel))
{
AddFueld(fuel.amount);
}
missing an out param 😛
gah mb im also playing fo76 😦
I see! I will try this once I fix this issue since I was going to make a fuel system anyway after this
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)
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
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
So like stacked rule tiles?
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
I can't find any documentation on it
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
Maybe three stacked grids, but the middle grid (the wall grid) rotates all tiles 90 degrees
Not sure what you mean with the rotation stuff
that actually worked
now i can paint the walls in on the second grid pretty easily
only issue is that the tiles clip
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
order layer fixed that nvm
I imagine they did this or something similar
this does sound more efficient though, but i have no idea how i'd make that in unity 2d
mixing sprites/normal mesh renderers isn't that bad (as long as render order is correct)
Yeah but the 2d tools keep it pretty simple
i am already mixing 2d and 3d
at my current skill level i don't think i could use anything off the tilemap though
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
did you actually install the package ?
Of course, installed, removed and installed again. Nothing worked
would be nice for a damn 3D tilemap :(
yea...sadly we only have GameObject/Prefab brush at best that works with Grid but not Tilemap.
I yearn to be whatever target audience the tilemap features we’re built for
are you using assembly definitions ?
What do you mean?
How would I use them?
I'm asking if your project has asmdef files
Yeah, I think so, how can I check?
search for any file that ends w .asmdef
forgot how to search by extension in unity search
I have these files, 2 of which are Cinemachine
They are called Unity.Cinemachine and Unity.Cinemachine.Editor
you need the find the one that contains your current script CameraScript folder
in that way you have to reference the cinemachine one
CameraSystem you mean? I don’t think any of these are using that because I made the script
what? you making the script has nothing to do with what was said... I know you made the script
I'm saying you should check if you have an asmdef file within your scripts folder
Or in a direct parent folder of it
I don’t.
Also no
if Scripts folder is inside Assets, are you sure that doesnt have an asmdef ?
I can't think of any other thing besides being asmdef since even unity wont recognize and not just ide
What's the one that's highlighted in that screenshot?
Yes 100%
It was a file I made as a fix, among finding fixes I talked to ChatGPT, which supposedly would fix the problem, it didn’t. It’s been deleted. Sorry, missed the message
Here you go
Probably time to show the code causing the error as its clear you did not make a custom asm def
Just as a probably relevant aside: the namespace these days is Unity.Cinemachine
So it's using Unity.Cinemachine and not using Cinemachine??
yea in vs you can make your field or var and use the lightbulb to easily add the using statement
No, it didn't.......
Is your IDE configured>?
!ide moment
💡 IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Sounds like it might not be
we need a counter for this too 😆
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?
Follow the thing that was just linked to you
You should do that before anything else
it will make your life 1000x easier
Thanks I will.
If I did that I wouldn't have spent 7 hours fixing a bug that essentially didn't exist
exactly
Is shader programming supposed to have autocomplete like C#? I'm brand new so I wouldn't know.
It's generally a lot more fraught. I don't think VS has any intellisense for it out of the box
Makes sense, maybe someday!
(Also shaders are not c#)
Yeah, shaderlab and hlsl
rewriting my movement script a whole bunch of times until it's absolutely perfect is a good idea right?
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
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.
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?
yeah, so i'll look for the problem then instead. probably a better idea since it's a long script anyway.
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.
Is it the space after :?
🤦♂️ - yes it was
It's weird it completely discards the entire expression when you do that though
That is weird... and weirder still at F2 actually shows in the output, because the {} is and expression block.
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.
Lool, right?
maybe the cs server could give more indepth answers
It's a custom format string as is
All characters that aren't a part of the format string are copied to the result string unchanged.
Are you seeing errors underlined in red in your IDE?
nope
Then you need to configure it. !ide
💡 IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
i cant find external tools
That's not Preferences
where is it at?
Edit/Preferences
thanks it was already configured
Well, some part of it isn't, or else you would have highlighting and autocomplete
i did everything i downloaded the package on both and it was set just like the image on the website for preferences
🤔 Unity, Huh, How?
If your IDE isn't providing autocomplete suggestions or underlining errors in red, then it needs to be configured.
did everything this link showed still no red lines
You commented out your errors and let Unity compile, and you installed the .NET SDK?
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)
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
show what you tried
in general - the answer is to use the DOTween extension methods for materials to start a tween like normal;
DOTween.To(() => myMat.GetFloat("MyValue"), x => myMat.SetFloat("MyValue", x), 0f, .75f);
DOTween has an extension for this you don't need to use DOTween.To
just myMat.DoFloat(....);
You can see in the docs https://dotween.demigiant.com/documentation.php
DOTween is the evolution of HOTween, a Unity Tween Engine
Ahhh, thank you, this is good! No idea how I missed that!
Small heads up that iirc you should be caching that material property getting via Shader.PropertyToID
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
Pretty sure both
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.```
Looks like you don't have the .NET SDK installed
Or you haven't restarted after installing it
do i need to restart my latop it never told me too i did unity and vs
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
Your computer
Just restart, it'll achieve the same thing
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.
It says you have no .NET SDK installed
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]```
You are using x64, so maybe you need to install that instead
ok its fixed now
Now, where have you defined the Collectable type?
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
but where is Collectable defined?
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
}
ah so the s messed it up then
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();
}
}
}
}
}
runtime errors wouldn't show in VS, only compile errors
The error is indicating line 34
which line is 34
Is it this one?
if (player.inventory.slots[i].type != CollectableType.NONE)?
if (slots.Count == player.inventory.slots.Count)
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
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
Where exactly is it ui supposed to change? Does it set a sprite to an image somewhere? Do you understand what the code does?
Did you do any debugging?
when do I know to use .normalized?
When you need a normalized vector
im honestly not sure what that even means 💔
Google it.
You need to understand the basics of vector math for gamedev.
ive been trying recently its been a struggle but ill understand it eventually
It's not that hard. It's something pretty simple among the things that you learn at school.
a normalized vector is like a compass needle, it always points in a direction, but its length is exactly one unit, that's what 'normalizing' does, so you can get a direction from a vector without plugging a bunch of speed floats in where they don't belong.
that makes sense, i couldnt understand anybody elses explanation so thank u
W usopp btw
thanks gang I love usopp
doesn’t Destroy() already do that
itl destroy the prefab itself
It destroys what you tell it to destroy. If you give it a reference to the spawned object in scene and not a prefab, then itll destroy the spawned object.
how do i know what name my prefab is though
I’m probabaky wrong 💔💔 but wouldn’t the name of your prefab be the variable you used to instantiate it
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
if the bullet is the one you want to destroy you'd destroy it inside the shoot function after some condition (for example time)
yeah i realized that i was trying to delete it from where i would shoot the bullet
and not the bullet itself
confused myself
😄
my fault for the naming being confusing
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)
does each component here need to know about every other component?
it seems like you've already seperated it into parts, so perhaps you could have like, submanagers to deal with each group
^ 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
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
why are they GameObject fields and not Button or TextMeshProUGUI 😐
yeah, a new project (for me) that was start in 2016
and can you not have 1 component to handle things for a player and then have instances for each player?
derp just realised its part not player 😆
Just to get whole 'pack' : button actions, text below it and lock image
i do not understand what that means
let me send a screenshoy
you named something Top_Text yet do GetComponent to get the text...
no i dont need a screenshot
oh you right for that one
If you have 1 gameobject with many objects (bad idea for ui things anyway) you should have a new script to handle them all
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 ?
Might need several system for tile to tile movement and a free movement. The former one does not need physics. It can be based on a grid system that keeps info on whether tiles are walkable or not. The latter one could be done with physics if you want.
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
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;
}
}
Look up how collisions work with tilemaps. You'd basically di the same as platformers, except not have gravity.
What color does change and what color does not change? What is an Outline?
never mind, i realized that i was only updating its value in OnValidate... 🤦♂️
Hey, I have an error saying that MyDailyRoutineManager script is null, so I suspect a racing / race condition, how to solve it please ?
Unity is single threaded
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
So I should subscribe to the event in Start() instead of Enable() ? 🤔
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
What if I go through my GameManager ? As all the references are centralized there 🙂
it honestly sounds like you have a spaghetti nightmare on your hands then
why ?
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.
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 😦
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?
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.
Define what's "proper usage" of singleton please, because I'm confused 🤔
not using them for every single thing for one
is it good ?
Whatever the script is attached to.
singletons are for centralized, singular systems
if you have a ton of singletons, maybe you have too many monolithic centralized systems
Which script ?
Here's my GameManager
Whatever the Null script is attached to should just be in the scene. That way the script will be enabled before everything else
What do you mean by "In The Scene" because it's attached to my HUD gameObject that's present in the hierarchy from the beginning but still has that issue
i explained why that is happening already
What is going on here 🤨
what do you mean ?
DayNightCycle could be an auto property in its current state and wont it be confusing having 2 collections with nearly the same name?
I will do that 👍
like so ?
So i should subscribe to those events in Start() rather than OnEnable, is that correct ?
Well if it's public it already has setters and getters.
Just by calling the object.
well no because then you aren't going to resubscribe when the object is enabled after having been disabled
Let us consult the ✨ Script lifecycle flowchart ✨
https://docs.unity3d.com/6000.0/Documentation/Manual/execution-order.html
i already told you that you should just be using a direct reference.
if I do that, I can't retrieve this property anymore through the class directly, so I guess I have to make it not static ?
you can still do that? there is nothing stopping you from accessing that static property
then there's something I don't understand somewhere
why did you change that line? you weren't accessing the static property through its Instance property anyway
I guess I can't make OnEnable() static otherwise it wouldn't make sense
but this does also seem like an abuse of static anyway
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
why would you need a static context for this?
That's what the error say
do you just not understand wtf static is or what your code was even doing?
I understood what my code was doing but right now not using the class directly and use a direct ref confuses me
look at the difference here and apply the same logic to your new code
the non-static context in question is dailyRoutineManager.
and, again, notice how you were not accessing CurrentRoutine through the Instance property anyway
yeah I understood that
so why'd you change the OnEnable lol
I have the same issue with dailyRoutineManager.Instance.OnDailyRoutineChange += OnDailyRoutineChange;
the whole point of the direct reference was to not be using the Instance property which was null at this point
yeah because Instance is a static member and dailyRoutineManager is an instance, not a static context
again, this is a clear misunderstanding of what static is and does and perhaps you should go review that
already did but it's confusing
static makes the member or the method belong to the class rather than the instance itself
yeah, and now you're trying to access a static member from an instance rather than the class
Oh Ok, got it 👍
Thanks
DailyRoutineManager.Instance is an instance of DailyRoutineManager, but you already have an instance right there, dailyRoutineManager
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 🤔
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
so what's the best way to avoid coupling (if there's any) ?
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
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
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
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
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 ?
Well you do it in a smart order duh
e.g. Init object A, load object B, init object B with ref of A.
I don't understand 🤔
But I think it's hard the bigger the project becomes, isn't it ? 🤔 So it's kinda hard to remember the order of everything 😬
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
That's why you plan your code
you can plan small parts at a time, but hard to plan the whole game all together at once
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
yeah
And yea it is difficult, software architecture is a whole field that people study for
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 😬 )
yes, that's part of the point of decoupling the objects
that means I have to flip my thinking upside down because I have to first add a call to a method of the receiving class from the sending class 🤔 ?
huh?
That's how passing a value works in any case.
@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)
can you explain what you mean by that first part?
this part ?
Class A : calling Class B method and passing the injection
Class B : declare the method that will receive the injection
yes
Let me write an example
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.
yeah possible because I didn't read much about it, but I remember seeing some stuff like that in minecraft code (Modding) and it confused me alot 😄
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.
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
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()
{
}
}```
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
I was thinking about the opposite, ClassB needing player from ClassA
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
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}")
}
}
that is the opposite of decoupling lmao
This seems very spaghetti-coded. Your references should be one-directional
When you have two objects that reference each other that's a telltale sign you're heading straight into spaghetti town
how isn't that one directional 🥲
ClassB sends itself to ClassA who calls a method on ClassB
yes to answer it and to pass the parameter player that's needed by class B 😬
also ClassB constructs ClassA
damn it, should I make the ClassA static to avoid constructing it ?
if ClassB needs the Player object but it also constructs ClassA, why doesn't ClassB just construct the Player object?
makes sense
Then one of the two:
- ClassB should reference ClassA and do
classA.playerwhen it needs it - ClassA should have an
eventthat calls a function with aPlayerparameter.ClassBreferencesClassAand subscribes to that event.
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
@somber nacelle @naive swallow Could you rewrite my code the proper way please ? So I can see what's the proper way of doing 🙂
public class ClassA
{
private Player player;
private static event Action<Player> OnPlayerSomething;
public void DoThing(){
OnPlayerSomething?.Invoke(player);
}
}
public class ClassB
{
void Start()
{
ClassA.OnPlayerSomething += MyPlayerWhatever;
}
private void MyPlayerWhatever(Player player)
{
...
}
}
But that's cheating 😦 You're using events, so it's not possible to do that without events ?
Because that's what I do for example in my DayNightCycle but didn't know that was called DI 🤔
How is that cheating
If you have a class that holds data and you want to push that data out to listeners that's what events are for
Because I thought that DI was independant from events usage 🥲
so does that mean that DI is always done through events ?
*through an event
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
Alright, but could it be done without events ?
I would rewrite it, but I don't understand what you're trying to accomplish.
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
hey! anyone got a minute?
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?
You outta cache those components instead of GetComponet every time you press a button
[SerializeField] SpriteRenderer spriteRenderer
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
You have a few options thay might be easier tbh. OnTriggerEnter and put a collider flagged "trigger". OnCollisionEnter which uses the same method, coupled with a RigidBody component. It really depends how your setup is, but it's a much cleaner and easier way to add collision detection on demand.
//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
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
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
What do you mean by editor code? As in code that I want run while in the editor?
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
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
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
That did the trick, thank you! It was a component's update method
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?
You'll need to at least tell us what you mean by "not functioning as it should". We can't read your thoughts or see your screen telepathically.
If you can't explain in words, record a video
that is what ill do
It’s like it snaps to the bottom right and doesn’t have much range of movement
The tutorial you followed looks like it's designed for 2d
In fact, it looks like it's poorly designed for 2D
Ok dang any way of making it work or should i look for a new one
At no point is the mouse position converted to world space
It seems to be mixing up world space and viewport space positions/directions
Oki hm any recommendations for a cannon tutorial or guide that will work in 3D
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.
Break down what you need .. for example cursor to world position & integrate it in your project. Doing some research will bring you further than looking for new cannon tutorials ^^
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
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 🤔
you can have baked animations for each weapon
or use IK
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?
okey, cool, ill give it a try, it just seemed like the most logical ease of use solution
So, question, Does this:
if (CanDrive)
Mean if the bool CanDrive = true then itle allow the code to run?
not a lot of items so i think ill manage, thanks for the help!
yea
Cause I'm running into Alot of issues with the my code haha
depends on what you want to do with that bool
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.
This is my code, absolute mess!
oh wait
its on ENter
not stay..
lmfao
Oh wait,
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
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 ""
OnTriggerEnter() you set canDrive = true
then in Update()
if (canDrive) -> do whatever you want here
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
i assume this code you sent is incorrectly sent?
why are there extra brackets and extra indentation in ontriggerstay
Because I'm a noobie, and don't knnow how to properly indent 😦
does extra brackets mean something bad?
with inputs you might want to check every frame
theres no condition here
why not use Unity's New Input System?
they are new and its harder to learn and most tutorials don't use it
Because my college course has us set on unity 2022
unity 2022 has it
ah i see
Eitherway, I don't plan on using it, as I need to learn to code.
you're still coding while using it
is your ide configured properly
there are a couple things wrong with this that shouldn't let you compile
biggest difference it makes is its easier to plug multiple devices
such as gamepads, keyboards, steam deck...
and makes your code cleaner
I don't need that, I only have two peripherals, my mouse and keyboard, don't plan on adding gamepad support, Just trying to get grades and get through college lmfao,
not make a triple A game HAHA
💡 IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
I'll clean the code up once it's working, just trying to figure out why my bool "CanDrive" is permantly set to false
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
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
thats more than enough
By autofills i mean only previouse things I typed
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
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,
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
Well i have boat movement,
does something enter the trigger? is that something tagged as the player? is f being pressed? etc.
gotcha
Seems to be working now, as its setting the bool to true.
only if im int he collider#
if it works it works 😄
but yeah use debugging to narrow down what your problem actually is
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)"
code formatting is backticks, `, not quotes
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?
they cant be changed during runtime
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
that makes so much more sense, silly i didnt think of that haha
im moving the fingers to make a grasp animation of sorts
thanks, that makes a lot of sense
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 🙏
whats the answer from
chatgpt is no help for this
it is against server rules to answer questions with unverified AI generated bullshit
#📖┃code-of-conduct
sry.
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
~~Have you looked at the actual documentation yet or just trusted AI bullshit?
https://docs.unity3d.com/Packages/com.unity.splines@2.8/api/UnityEngine.Splines.CurveUtility.html#UnityEngine_Splines_CurveUtility_GetNearestPoint_UnityEngine_Splines_BezierCurve_UnityEngine_Ray_Unity_Mathematics_float3__System_Single__System_Int32_~~
ive used GetNearestPoint() in the past just fine
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)
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
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
You're logging t?
I've only used it with things with 1 spline but 3/4 knots
yes
is this 1 spline and in a SplineContainer?
yes
are you sure you are transforming the position correctly like in my example?
to spline local, then back after
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)
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
It is an object in the world, so it's going to be affected unless you adjust it by FOV, like you say. This sounds weird for something you want in the game world, though. Maybe you want something as an overlay that tracks along with items in the world instead?
Yeah I don't know lol
I'm basically trying to make my HUD get affected by postprocessing, but it seems like you can't really stack cameras anymore without it kinda "duplicating the post processing" which is what happens with overlay cameras so I'm not sure what to do
Maybe you want something as an overlay that tracks along with items in the world instead?
What do you mean by this exactly?
Is it a VR game?
No
then why use world space canvas?
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.
So the ui can have post processing lol
you can do that with a Screen Space - Camera canvas
Hm lemme check
💀 I think you may be right haha
wait it is weird tho that it still gets affected by fov
depends what kind of effect you're talking about
?
If you mean the pp effects, im just using a buncha custom effects from some assets that just change the graphics and stuff
Oh lol - I think it mostly just changes the position and a little scale and rotation
A screenshot would be nice
Okay here are the differences between high and low fov from different views
So this is like a player stat (health?) and not something that needs to be in-world for some reason?
yup
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 🤔
yeah ive been struggling with this for hours lol
but seems to be a big problem, there was some solution and like tutorial at the very bottom of that thread but it kinda just solved it for some post processing effects
i did yeah - dont know if i did it 100% correctly but I followed all the steps. our renderers do look different tho, and different things happened - maybe cuz im using compatibility mode and custom shaders idk cuz i didnt have access to the render graph viewer either
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.
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
Finish a sentence, then hit enter
anyone? my time is running out
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
can you be more specific about "isn't working"
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 🤔
It's not clear what you mean by keeping the hand at its "original position"
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
aight, ill give it a shot ty (nvm, fixed it)
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
vs code is confused about what this project is using. try re generating the proj files from unity preferences
