#archived-code-general
1 messages ยท Page 352 of 1
The object always has a connectedobject assigned
And yet it attempts connect
And it passes the condition of NOT having an object assigned, even when it ALWAYS has an object assigned
Actually, it DOESNT always have an object assigned apparently
Even though nowhere in the code does it remove it
Connectedobject isnt modified anywhere in the code
At all
There are only that many options:
- it's never assigned
- It's removed at some point
Proper debugging would help figure that out.
It's assigned at all times, except seemingly when something with a WireConnector script collides with it
It's initially assigned in the inspector
And it's not like it gets unassigned or anything
It always shows up
Can you start from clarifying what exactly is assigned or not assigned?
the connectedObject variable
Trying to serialize a hashset for use in the editor but I don't seem to be able to actually edit the list to make changes
[System.Serializable]
public class SerializableHashSet<T> : ISerializationCallbackReceiver
{
private HashSet<T> hashSet = new HashSet<T>();
[SerializeField]
private List<T> serializableItems;
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
this.serializableItems.Clear();
this.serializableItems = new List<T>(this.hashSet);
}
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
hashSet.Clear();
foreach (T item in this.serializableItems)
{
_ = this.hashSet.Add(item);
}
}
public bool Add(T item) => this.hashSet.Add(item);
public bool Contains(T item) => this.hashSet.Contains(item);
}
What am I doing wrong here?
I am supposed to be getting a reference. I always do, except for when the object collides with a WireConnectorObject, the reference becomes null and the else condition passes
How/where do you know that the reference becomes null?
A Debug.Log(). When the (connectedObject || connectedSocket) case does not pass, I print what connectedObject is. It returns null
What's with that underscore in deserialize?
This??
if (connectedObject || connectedSocket)
{
Debug.Log(gameObject + "passed first case");
}
Yes. I print the value of connectedObject if that or condition DOESN'T pass, and it prints that connectedObject is null
I don't see any debug log printing the connectedObject
Yeah, I added it in after the fact
Share the updated code then
my bad, that was an old version with some non working parts. Here is the corrected code
public class SerializableHashSet<T> : ISerializationCallbackReceiver
{
private HashSet<T> hashSet = new HashSet<T>();
[SerializeField]
private List<T> serializableItems = new List<T>();
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
this.serializableItems.Clear();
this.serializableItems = new List<T>(this.hashSet);
}
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
hashSet.Clear();
foreach (T item in this.serializableItems)
{
this.hashSet.Add(item);
}
}
public bool Add(T item) => this.hashSet.Add(item);
public bool Contains(T item) => this.hashSet.Contains(item);
}
Well, I don't see you assigning that variable anywhere, so for example, if it's a new component or instance, it might not have it assigned. If anything, I'm not sure how you can be so confident that it's assigned with that code.
Assuming the serialization callbacks are called correctly, I don't see any issue.
im watching a tutorial, and it is a bit too advanced for me and its hard for me to understand the code hes writing
right? That's what I thought
You can confirm that by adding a debug log.
I put code in update to, if it has a connectedObject reference, print that it has a reference. They all do
This has to be a Unity glitch
I'm so confused
I would suggest modifying both structures at the same time, e.g.:
public bool Add (T item)
{
hashSet.Add(item);
seriaizableItems.Add(item);
}
That way you ensure structures have the same content at any time.
Add a second parameter to the debug log passing in this. When the null message prints, click it and it should select the object that printed it.
Then you can confirm if it has the reference assigned or not.
It's worth searching terms like "basics" or "for beginners", cause such tutorials would be created with beginners in mind. After watching such videos it will be easier to transition to more complex ones.
alright, thank you
https://youtu.be/8eWbSN2T8TE?si=YX9baBeVqyF2QFlB just in case ill send the tutorial (im not asking for help on it)
In this Unity tutorial, I will show you how to code a simple patrol script in C# that can then be used in what ever 2D or 3D game you are currently developping !
Basically we will get a character randomly moving around a scene, wait X amount of seconds before moving somewhere else !
Here is the link to the HOLE AI PLAYLIST : https://www.yout...
I'm not sure what to tell you
I did this
I didn't really learn anything new
Depending on your settings, it's possible that you fixed it awhile ago and your domain just didn't refresh until now.
They all have the reference until suddenly they don't
Then it's unassigned somewhere. Remember that destroyed objects are also considered as null in unity.
You could use a property and throw a debug.log whenever the value is changed to see where it's being altered from
The object is never destroyed
That's the problem - the value is NEVER CHANGED
apparently your result says it is though
I know ๐ญ๐ญ๐ญ๐ญ
So just make it a property and check
What do you mean
Like show it in the inspector?
No just use a C# property and a backing field
Not sure what those are
public string Property
{
get => _backingField;
set
{
_backingField = value;
Debug.Log($"Property has been changed. {value == null ? "Null" : value}");
}
}```
I don't think this will help me. I have an equivalent of this already
use your original variable name for the property so you don't need to change any code and just add a backing field.
that way all changes flow through the property
Really quick question - if an object gets floating point errors can that make it lose a reference
floating point error is just mathematical inaccuracies building up, not an actual exception, so no
I really don't know how to implement the backing field thing
This video doesn't explain the basics, but it should be easy to understand for people who already know them. I assume the creator haven't explained the basics, because AI patrolling seems like a moderately complex topic (which implies that people with moderate knowledge will watch it), and he assumed everyone who doesn't understand the basics will watch his previous videos. Here is his playlist of videos about basics:
https://www.youtube.com/watch?v=pFeWUSWHIdk&list=PLBIb_auVtBwD5ovBwgGKbQK8d7efdKGlk
thank you, i really appreciate this ill watch it right now
it's a concept you're going to want to be very comfortable with anyway, so worth spending a few minutes on
the tl;dr version is that if my code has Property = "bob" then first _backingField will be set to Bob, and then it will log. It's a handy way to monitor and act on incoming changes
If we wanted to add an OnChange event whenever our variable was changed for instance, we'd just stick it right there in the setter and ensure nothing was accessing the backing field except that property (which is super easy to confirm in your IDE)
Restarting Unity seems to have fixed it
lovely
I'm trying to add a field to my SO that calculates the sum of other variables in realtime, but I can't seem to get it to display (even using NaughtyAttributes)
Does anyone have any tips on solving this?
u can tell unity to serialize the backing field of that property with
[field:SerializeField]
I thought so too and tried that but it doesn't draw the field and pops out this error ' 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored.' ๐ค
that only works for properties that have a backing field, Base_Total doesn't
ah my bad i didnt even fully read to see this was just a getter
what's a backing field? ๐ฎ brb googling
i don't use NaughtyAttributes so i don't know what it supports but in plain unity you'd need to write a custom editor for that type to display a property like that, it'll never be touched by unity serialization since it's effectively just a method
that sounds more complicated than it's worth tbh
couldnt u also just give it a private set?
yeah i just bought odin for stuff like this ๐
only if you deleted the current getter so it was an auto-property, which defeats the purpose i think
hey guys, how can i make an object lock to the cursor? i wanna make a flashlight stick to the cursor the whole time
i have a custom cursor as well currently and a cursor manager and this is the code i have:
`void Start()
{
cursorHotspot = new Vector2(cursorTexture.width / 2, cursorTexture.height / 2);
Cursor.SetCursor(cursorTexture, cursorHotspot, CursorMode.Auto);
flash.transform.position =
}`
trying to do anything in Start will achieve nothing. you need to lock your flashlight to the mouseposition in Update
- Get position from mouse
- Calculate angle from object towards mouseposition
- Set rotation of object with calculated angle
You may be able to just set transform.forwrd/up/right to the direction-to-mouse vector
unity error while evaluating property 'namespace' of task ':unityLibrary:packageReleaseResources'. See the Console for details.
i get this error when i try to make an android build, what should i do ?
and i started getting the error after switching from unity 2022.3.8f1 version to 2023.2.16f1
why would you switch from an LTS version to a non LTS version ?
i want to use the addressables for android asset and its only available on 2023 versions
in that case at least go to the latest Unity 6 Preview version
umm im not sure what that means tbh
Unity 6 Preview is what would have been under the old naming convention 2023.3
this ? @knotty sun
yep
ok i will try it out, thanks man
Adressables are available in much lower versions than 2022... is 'Addressables for Android asset' something different?
yeah sadly
yea same, i wonder why it says 2023.2
maybe older adressable package version works on older unity versions
Right, this is an addon to the Addressables package
yea, it's com.unity.addressables.android package
The Addressables for Android package works in conjunction with the Addressables package to support Play Asset Delivery and provides you tools to pack Addressable groups into Android asset packs. This way you can take full advantage of asset pack based dynamic delivery.
what do i have to do ?
do i just download git ?
I have been thinking and want to understand how to properly build the logic with Zenject. I may have MonoBehaviour components, but I think it's not just about using two interfaces and "cluttering" the container with dependencies that always need to be injected into MonoBehaviour through a custom constructor method.In general, I am thinking of starting to create objects from prefabs at the moment of initialization/dynamically. Here, I don't fully understand the correct approach. Yes, there should be a service that handles configuration delivery, and a factory (here, I don't want to use a Placeholder because I think it will require a lot of injections and writing code, which isn't a problem).Suppose I have a player who will have scripts like PlayerSpawnPoint, IPlayer, PlayerProxy (can it be used to hide the implementation? Here, too, I don't understand if it's necessary to use an interface for the factory and proxy implementation - I think not). Some kind of PlayerBehaviour and so on will also be needed, and everything should be covered by a facade.It's interesting to create the player at the level of GameObjectContext, that is, through PlayerInstaller or not.
My main problem is that I don't fully see the application architecture. Of course, many implementations are possible, but I want to finally try dynamically creating objects, attaching components, using an asset provider, and developing smoothly. I sincerely ask for advice, as I'm still far from being a Unity expert.
yes, you can install GitHub Desktop which should do the trick, although this looks like a samples package so you might just want to continue
oh ill just press continue then
When I am lerping my gameobjects transform when using time.deltatime as t myobject flickers really fast from a and b
Why is this happening?
because that is not the way Lerp works
Wdym like I have a which is objects starting position b which is final position and t when it's set as time.delta time it's flickers really fast
t should vary from 0 to 1. deltatime does not do that
Oh yeaaa
But there are many scripts that use that and it works
I did it yesterday for a object and it seemed fine
bet, they may kinda work but I can guarantee you they do not actually work
I got it
Time .delta time only works
If a is the current player pos
It's not a good solution
Cuz u can just use smoothstep
And get a more accurate result
yep and even then it doesn't actually work because end pos is never reached
Yeye
So imma just use smoothstep
i dont think smoothstep is what you want either if you're using deltaTime as the 3rd parameter
there is Vector3.MoveTowards, the 3rd parameter takes in a max distance to move which sounds more like what you want
@lean sail Remind me, is this a Brackeys screw up ?
Is it not possible to inherit from Component instead of MonoBehaviour ?! I'm pretty it used to be a thing
honestly not sure, ive barely seen his stuff.
I've seen this misuse of Lerp so many times, it must be coming from some popular bloody awful tutorial
from an old post https://discussions.unity.com/t/there-are-some-big-issues-with-unitys-lerp-tutorial-who-can-i-talk-to-about-it/563742 it seems like unity had it in a tutorial at one point. im guessing if brackeys or other modern day youtubers are doing it, they're all just copying off each other. In which case someone first copied it from a bad example
jfc, that's from 9 years ago, I despair
is there something you're trying to do specifically by having it derive from component instead of monobehaviour?
I am very confused why a materials list refuses to update but a single material does - if I do someRenderer.materal = something; that works fine in changing the first element to "something" - if I do for(int i = 0; i < someRenderer.materials.Length; i++) {someRenderer.materials[i] = something; Debug.Log(someRenderer.materials[i]);} that doesnt change any element to "something", and since .materials creates instances, I also tried using .sharedMaterials which gave the same result and I dont understand why, maybe its too early here, am I missing something? Do I have to do some kind of renderer.ForceUpdate or something? Why does changing the first element with .material work and not the list with .materials? Nothing else affects this renderer (these are also standard HDRP materials, so no custom shader logic involved)
A script that doesn't use any of the Unity callbacks. It's literally just a component, doesn't need any Update etc
the materials property returns a copy of the array, you need to update that element in the array and reassign it back to materials
if you're doing this frequently, you can use GetMaterials and SetMaterials to avoid the allocations from copying
Ah, alright that confused me, I thought I could update the materials list directly from a renderer reference - thanks for the info on that
then just make a class that doesnt implement any of the methods. I dont know if you could do what you want awhile ago, but iirc Component is just used for unity's built in components like Rigidbody uses it
Is it possible to make one animator update before another without manually ticking it? I'm considering playable API but not sure if it's feasible
Hi, I have a weird issue, when I initialize the IAP for googleplay I get this error:
Initialization Failed: NoProductsAvailable No product returned from the store.
I have products in my catalog, I imported in google play, made a closed beta version, configured the IAP service in unity, but it wont initialize correctly. any idea why?
public class DirectoryWatcher : MonoBehaviour
{
// A class watching for any new files in a directory //
public string m_FolderPath;
private FileSystemWatcher m_Watcher;
public GltFImportManager m_ImportManager;
private void OnEnable()
{
m_Watcher = new FileSystemWatcher(m_FolderPath);
m_Watcher.Filter = "*.gltf";
m_Watcher.IncludeSubdirectories = false;
m_Watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
m_Watcher.EnableRaisingEvents = true;
m_Watcher.Created += OnCreated;
}
private void OnCreated(object sender, FileSystemEventArgs e)
{
Debug.Log($" created sender {sender}, {e.FullPath}");
m_ImportManager.LoadObject();
}
private void OnDisable()
{
if (m_Watcher != null)
{
m_Watcher.Created -= OnCreated;
m_Watcher.Dispose();
}
}
}
public class GltFImportManager : MonoBehaviour
{
public string m_AssestURL;
private ImportSettings m_ImportSettings = new ImportSettings
{
GenerateMipMaps = false,
AnisotropicFilterLevel = 3,
NodeNameMethod = NameImportMethod.OriginalUnique
};
async public void LoadObject()
{
var gltf = new GLTFast.GltfImport();
var success = await gltf.Load(m_AssestURL, m_ImportSettings);
if ( success ) {
var gameObject = new GameObject("gtlf");
await gltf.InstantiateMainSceneAsync(gameObject.transform);
GarbageItem item = new GarbageItem(0, gameObject, Random.Range(20, 40), gltf);
} else {
Debug.LogError("Loading gltf failed!");
gltf.Dispose();
}
}
}
Hello, I'm running into an issue where my system file watcher is not successfully executing asynchronous event for loading objects. Any help would be appreciated ((:
You're accessing/creating unity objects on a background thread
You did
new GameObject();``` and ```gameObject.transform``` in a background thread. Neither of those are ok.
is the Created event on a FileSystemWatcher always called from a background thread?
i guess in that case you could put in an await Awaitable.MainThreadAsync() at the top of LoadObject
ok thank you. makes sense - I will try that!
should i just press yes ?
no luck! any other idea how I could go about doing this?
do you get an error or anything? how do you know it's not working?
the function doesnt run
Sorry, I have a debug message at the top of LoadObject, which doesnt get called, even after adding the Awaitable.MainThreadSync()
and is the one in OnCreated being logged?
yes, the oncreated is being logged, and it is called
I want to make a 2d game with a fairly advanced movement system and I'm wondering about the benefits of an Event-based Manager or Action Queueing over a State Machine, I havent used Action Queueing before
Oh nevermind, there was an issue on my end. Working now, thank you so much!!!
aha, nice, i was about to say it didn't make sense that you were getting one and not the other ๐
just so I understand it correctly, what is the Awaitable function doing?
it's a Unity helper for doing exactly this, when you await it'll resume execution afterwards at the next Unity async update, so usually on the next frame somewhere between Update and LateUpdate
on the Unity thread, of course!
Awaitable is unity's own version of Task fwiw, there's various other useful helpers in there
ah ok. I'm only learning about threading over the past week ..confuses me slightly! and so, the reason it doesnt work without that call is because OnCreated is synchronous, and doesnt await my function?
no, it's just that OnCreated is being called from a thread other than the Unity thread in the first place, i assume because that's how FileSystemWatcher works (i've never used it)
oh yes, its a background thread - okay makes perfect sense
So, I'm making an inventory system and I was wondering how you'd keep track of the items on which spot. Currently, I'm using a list with all the items (item on listnumber 3 stands for spot 3 in the hotbar).
But if you remove an item, all spot change. What should be the best way to keep track of the position instead of a list?
Assign item as a children of the slot it in?
Ah, referring to the slot itself. thanks!
Why didn't I thought of that.
What if I add an entire inventory with example 30 extra slots. Wouldn't it be bad if I have 30 same scripts in my game?
Why would it be?
I don't know. It feels kinda wrong having 30 same things running the same time. I'm probably just overthinking it. I thought it'd take a lot memory
for me it doesn't, for some reason
wat
Check your spelling
I mean I am following an 7 year old tutorial but ig you are right
what did I spell wrong? could you specify more?
Also your log is inside an if statement so even if you fix that it might still not run if the condition isn't satisfied
The name of the function, as I mentioned
OnCollisionEntered is not a Unity message
yea I do want that
Sure but it makes things harder for you to debug
how does it make it hard? I want to know when the object collides with the obstacle, so should I not use an if statement?
and what do you do when nothing get's debugged?
that means that my player ain't colliding
no it doesn't
Hey guys, I've been developing a VR based Squash game and facing some issues in collision between the Racket and the tennis ball, I've tried to write the script for both of these dynamic objects but something is still felt missing, I am dropping both of the scripts below, kindly help..
Hi guys, i am building a linux build using IL2CPP on my Mac (silicon chip) for a dedicated server, and it's taking forever on the Linking GameAssembly.so (x64). Is it normal ?
hi
yes it normally takes a long time building projects with IL2CPP because it converts C# code to C++ before compiling, which takes a lot of time. Also the GameAssembly.so file is pretty large and complex binary, so linking that will also take alot of time.
but you can speed it up for example: by using burst compilers and incremental builds
actually unity uses incremental build pipeline by default for release and development build
ok thank you
any fix for this ?? i get this random blue area that covers a part of the map in game view for some reason
is your camera in orthographic mode? is it rotated slightly more then it should?
wow
i would have never figured that out
thanks alot man its fixed now 
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ 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.
How come my method isn't appearing in the button function, when the method is a public void? https://gdl.space/pahaloweta.cs (RotateObjectAt is the method I am attemptig to call)
which method
RotateObjectAt?
Yes
It's because it has two parameters
UnityEvent only supports a single parameter for the inspector
interesting, so my only fix is to remove one of those parameters?
Or remove both parameters
You could separately serialize the parameters as fields
and just have a wrapper function without parameters to call this function with your field values
Yeah that should work
Alright thanks
in my game i have a arm holding a torch, when i look up and down both of them kind of stretch for some reason, but looks normal when looking forward
like this
Don't crosspost
also this isn't a code issue
sorry
Hello everyone, before I added a background video, my circles could glow (first image), but right after adding the background video, the glow disappears (second photo shows that if i lower the alpha, the glow can be seen there)
I honestly dont know how to fix this
Hey guys! I'm making a metroidvania and I'm having some trouble figuring out how to program the abilities. I don't know what's the best and most modular way to implement them. Can anyone help?
What is a good way I can find other beginners to work with :D ?
Unless you have multiple characters with multiple abilites - you probably don't need the best and most modular way to implement them ๐
But other than that... I guess separate each ability to a separate component and make a prefab with it, and make it so that you can add any of these prefabs to the player and they'll do stuff on top of the core player components (you'll pass components and stuff around when initializing the abilities)
But my personal approach to anything that I can't imagine how to make nicely is... just make it work and see when it starts being annoying to work with and refactor until it's good ๐
In the game I want the player to have 2 ways of combat. The main way is through a melee attack. The second way is through a revolver which is charged by hitting the enemies with the melee attack. Down the road I intend to add more abilities such as dashing, a charged melee and revolver attack, etc. For now I have a player controller which handles only the input, a player movement, a revolver script and a melee attack script
Nobody knows what might be causing this?
first guess: use an unlit material for the background video
your video player renders to a render texture, which is assigned to a material. change this material to be an unlit one
let me check this!
Are you looking for feedback or just sharing your approach? Its a bit unclear to me if there is a question here
im not quite sure where to change that material, honestly i dont see any material section in the inspector
Is it rendering in world space or UI space?
I'm sorry, I don't like my implementation so far and I'm not sure what other way I could implement abilities
I'll need to look into how the video player works again
Layer is default so i guess world?
But my previous background image was also on default layer and the glow was working
Ah, I see- maybe you could look into FSM (Finite State Machine) and implement a similar pattern with "states" or "sub controllers" for your input and abilities these states/sub-controllers can also use [System.Serializable] so you an edit them in the inspector and dont need to derive from MonoBehaviour - or you could look into interfaces with abstraction and generic classes, which would be a more code solution that wouldnt use the inspector, the abilities themselves could be inherited classes or possibly a list of ScriptableObjects that 1 mono script initializes/updates - if your using the "new" input system, you could also subscribe events for input to have certain keys call certain ability indexes, I do something similar for a "hotbar" in one of my games
I'm thinking about making a monobehaviour script attached on the player that holds all of the abilities which are SOs
So basically a list of SOs that derive from a base class
you dont have to hold all the abilities, hold the current one
swap out when needed
if you place your SOs in the Resources folder you can Resources.LoadAll
But what if I have a revolver, a dash, a double jump, etc?
how many abilities can the player equip at once
No idea, since it's a metroidvania, the player will gradually unlock more abilities as they progress through the game
So all of them basically
Should I use a map instead of a list?
Would be easier to call each SO ability from the player controller I think
that's hardcoding โ
the base SO will have different functions you can override like OnJump, OnShoot, OnMove etc
you can call the according functions in the player controller but don't hardcode it
I was thinking the base SO would have a function TriggerAbility and each derived class implements it differently
And the player controller would call that function depending on the key pressed
For example OnShoot would be something like: abilityHolder.UseAbility("RevolverAbility")
And UseAbility triggers the function of the specified SO
(If I would use a map)
Anything string based like this will be a pain in the ass
Idk man, I'm not too good when it comes to system architecture
you can use System.Action, it's like a list of functions.
System.Action onDeath;
public void deathEffect() {}
...
onDeath += deathEffect;
calling onDeath.Invoke calls deathEffect
you can add many functions to one System.Action
hmmm, no
Your SO approach is not bad, but replace the strings with enums
Oh
I see what you mean
But how would I call a specific ability from the player controller?
abilityHolder.TriggerAbility(???)
I mean how do I pass an enum state to the function
say you have an enum
public enum Ability {
RevolverAbility,
// More here
}
then
abilityHolder.TriggerAbility(Ability.RevolverAbility);
Is the enum in the player controller?
and the method signature is
public void TriggerAbility(Ability ability) { }
enums are a type, they can be anywhere
So its in both scripts right?
no, generally I put public enums all in their own script
Ah, I didnt know I can do that
basic C#
Either is good, whatever is easiest for you
a map is just faster
Which would you personally choose?
Dictionary is so much simpler if this is the use case I think it is
I think a map is better cause its easier to work with strings than with index
well they'd be using their enum not a string
dictionaries/maps work like arrays
Yeah you get my point xd
in fact for c++ we just use enums for arrays
I would use an array, but I'm a stickler for performance. A Dictionary is probably easiest for you to implement without problems
no
not out of the box by unity*
And I would need them to be right?
you can easily serialize them manually
there is an easy workaround using the ISerializableCallback interface
I have to say, I highly dislike those enums that tend to grow indefinitely over time... I'd rather use const strings (or not strings, but strings are "easy")
that depends on what you're doing.
What if I just load all the abilities from the project files into the dictionary and assign each key as the SO file name?
yeah, and when you profile your game because the FPS is shite, the first thing you need to do is remove/replace those strings
only if you're using them a frogload per frame... ๐คทโโ๏ธ
has never practically happened to me even on mobile dev... but if performance is a problem - yes, you'd replace them with something better... still not an enum, because an enum like that binds things together (things that are unrelated, to a large degree)
It's not like const strings are gonna be used differently or are more performant. This would just make it a pain to assign in inspector if needed
The performance impact of using const strings is probably minimal and insignificant, because they are interned. That said, you should still use something else rather than strings for other more important reasons.
Isn't this basically equivalent to an enum in most important ways?
You don't have to stick them together. Adding a new implementation of the thing no longer requires adding something to an enum, and in a sense changing existing code.
Perhaps I'm biased, as I've seen these enums go out of hand way more than I'd like... ๐ฆ At some point people add switches and if's over them and suddenly when you add a new thing, you need to find all usages of the enum and adjust that code as well.
Enums just make it very easy to feel like it's an exhaustive well-defined list of things
when you add a new thing, you need to find all usages of the enum and adjust that code as well.
There are diagnostics for that.
If you use strings, there's truly nothing that can help you, unlike enums.
That's partially fair, but the thing is, you're less likely to mess it up like that, as you wouldn't have the same expectations as with an enum
(I'm not a fan of random strings, let me clarify that... but if they're consts and not eating performance... ๐คทโโ๏ธ )
Any sensible defensive programmer is doing this:
switch (thing) {
case A:
case B:
default:
throw new Exception($"Unrecognized case encountered: {thing}");
}```
And, of course you conveniently over look the fact that a string takes up 2 bytes per character whereas you can store 256 enum variations in 1 byte
IDE0010 and IDE0072 will emit warning when you modify an enum and the switch no longer handles all the cases. You can turn that into a compiler warning (bonus point for turning on warning as error) to actually enforce the problem you are talking about.
If you use strings, there's truly nothing that can help you.
cs
//using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public float radius = 200f;
public float power = 10f;
private void OnCollisionEnter(Collision collision)
{
Vector3 explosionPos = transform.position;
Debug.Log(explosionPos);
Collider[] colliders = Physics.OverlapSphere(explosionPos, radius);
Debug.Log(colliders);
foreach (Collider hit in colliders)
{
Rigidbody rb = hit.GetComponent<Rigidbody>();
if (rb != null)
rb.AddExplosionForce(power, explosionPos, radius, 3f);
}
}
}
guys does anyone know y the sphere overlap wont detect any colliders in my scene
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ 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.
Really suggest anyone that uses enums to turn these on and have them enforced in your build.
There might be much better ways to organize, of course, by not dealing with such things at all... and mostly just using objects, refs and interfaces, and not some form of IDs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public float radius = 200f;
public float power = 10f;
private void OnCollisionEnter(Collision collision)
{
Vector3 explosionPos = transform.position;
Debug.Log(explosionPos);
Collider[] colliders = Physics.OverlapSphere(explosionPos, radius);
Debug.Log(colliders);
foreach (Collider hit in colliders)
{
Rigidbody rb = hit.GetComponent<Rigidbody>();
if (rb != null)
rb.AddExplosionForce(power, explosionPos, radius, 3f);
}
}
}
does anyone know y my sphere overlap isnt detecting any colliders in the scene
Again, memory is the cheapest thing nowadays, you're extremely unlikely to eat a reasonably amount of it by having 1000-2000 strings ๐คทโโ๏ธ premature optimization and all that
please follow the instructions from the bot
im trying xd
You can literally copy and paste this part
This is a problem, because this code now needs to be adjusted, and is even worse than what Burrito is suggesting, because at least with Burrito's approach you'll get a compiler error (right?), and with this you'll get extra sad at random runtime
ye mb i though it was just to add cs lol
Using strings doesn't save you from actually having to implement code that handles a new case being added
It pushes you away from thinking this code is a good idea in the first place
Because it makes it less convenient / even more weird to write it in the first place
Strings are interned, you can have 1000 occurrences of "foobar" in your source code and there will only be one copy of it at runtime, and comparison of them will be just as fast as comparing two objects because it's just comparing two addresses.
I think the performance impact of string vs enum should not be the center of this conversation, but rather all the organizational issues and the fact that they are practically reinventing a language feature in their own unsupported way and thus missing out all the existing tooling benefits (like the diagnostics).
enums are great for days of the week or months or anything that's well defined and won't be changing all the time
does anybody know?
I guess I'm trying to understand what this alternative you're suggesting is that's somehow better
And what's so bad about an exception
It's 100% not better, it has the exact same issues as enum but more.
If you add a new const string, it's not any better than adding a new enum member.
Except you get no help from diagnostics to tell you to update your existing code.
imagine if instead of an exception you just left out the default case in your switch. Now we just silently fail instead of loudly failing
and our bug goes undetected for weeks
no, no, exceptions are great, I'm saying that compiler warnings and errors are better, as those can help you even earlier in the dev cycle
and fine, I'll agree, probably strings aren't better
just pass instances or something around
the point is to not need a list of all things that are kinda unrelated... like all abilities... you shouldn't need one place that knows about them all and does stuff with them
Have you verified that your OnCollisionEnter() method is executing, and debug-drawn the sphere or flipped on the Physics Debugger's query drawing to ensure that the sphere is where you expect, and does indeed overlap with non-trigger colliders?
Hey everyone. Is there a way to set a texture.jpg to a material as the Base Map in a script?
and that's what an enum like that is... a place that knows about all of them... then people start using it as such, then adding new ones becomes a problem
the on collision enter works but how would i debug to see where the sphere is
It seems I can set the normal map image just fine, but for some reason I can't figure out how to set the base map image
Window > Analysis > Physics Debugger > Queries
It really is not if you have compiler helping you whenever a new variant is added.
So I'm using a buoyancy effector2D on a water object that's using a polygon collider. If my character floats over a quad edge in the water, they get effected by twice the buoyancy and float in place. It seems like there might be no way to avoid this?
Enum represents an exhaustive list of possibilities (kind of, C# enum doesn't exactly but that's besides the point), if you have compiler to help you ensure that exhaustiveness, then you are good to go.
it won't help you if you have a default case or if you just have a weird if that now needs to be adjusted
the sphere is where its supposed to be
The diagnostic will still warn you for trying to use default case to ignore everything else.
Ah, okay, so then you can't use default, which is a problem in some of these places... or again, you just used an if to check if it's 3 of those now 26 enums
and now there's a 27th... what do you do? find all instances, think of what was the intended behaviour in each place, get sad, spend time, etc...
if they have different behaviours and you're constantly adding new ones, then you should have proper objects that you're passing around, with properties and whatnot
and then you don't need one place with all the IDs (the enum)
You absolutely can use default, in fact, you must use default.
And there are Game Objects with non-trigger colliders within/touching it? What is your Debug.Log(colliders) logging?
empty
its not getting any of the colliders for some reason
I suggest you to take a look at the links of those diagnostics, if you have an enum:
enum E
{
Foo,
Bar,
Baz,
}
The rules will enforce you to write code like:
switch (e)
{
case E.Foo:
DoFooStuffs();
break;
case E.Bar:
DoBarStuffs();
break;
case E.Baz:
default:
DoDefaultStuffs();
break;
}
When you add a new variant to the enum, you are forced to also add a new case (even if you are going to just ignore it and let it handled by default), forcing you to acknowledge it.
You are also forced to always have a default case.
any idea y this is happening @wide terrace
I see, I see... so it'll get a bit verbose? It is a cool feature that I did not know about ๐ ... but I'm saying those just shouldn't be enums in the first place. Logic should be inside some object implementation and not in a place that knows about ALL things that you're changing all the time.
Open-closed principle or something, right?
Well this is arguing for object oriented programming basically
And polymorphism
Which has its place but also its own drawbacks
Hmmm... the code looks fine to me. And layers shouldn't be a problem since it defaults to all layers. I'm not really sure :/
I'll try to make a small replication really quickly, just to see if I'm not overlooking something obvious. But hopefully someone else might have a better idea
alr thanks for the help
Polymorphism also requires you to put the handling code on the object itself, which is problematic in its own rights.
Same as enums - they're great for stuff that's very localized and/or constant, very annoying if you need to modify it every time you want a new implementation of something
You are essentially pointing out the expression problem: https://en.wikipedia.org/wiki/Expression_problem
The expression problem is a challenging problem in programming languages that concerns the extensibility and modularity of statically typed data abstractions. The goal is to define a data abstraction that is extensible both in its representations and its behaviors, where one can add new representations and new behaviors to the data abstraction, ...
In object oriented code, adding a new variant is easy, just add that new class; but adding a new operation is hard, you need to now modify every single class.
In functional code, adding a new operation is easy, just add that new operation and switch on it; but adding a new variant is hard, you need to now modify every operation's switch.
They both have their problems, you might be only seeing half of the expression problem, the half that favors OOP.
Change your Debug.Log(colliders); to like Debug.Log(colliders.Length);, just to be sure - it looks like colliders do not serialize into a string, so logging the array may be misleading
I guess the next thing to check is if your game objects with the colliders have a rigidbody (on that very same GO - not on a child/sibling/parent etc)
ya they have rigid bodys
how do i change to make it look for things in a specific layer cuz i have a feeling that might fix it
@wide terrace do yk how?
thanks @chilly surge didn't think of it that way and didn't know about the expression problem...
still, the use-case was specifically about an enum of IDs for SOs that define abilities... that's bound to grow whenever they want to add/experiment with a new ability, plus they already have an object that they can work with ๐คทโโ๏ธ not using said object and doing any magical ifs/switches on IDs is making the system way more annoying to extend, wouldn't you agree? because now the logic is all over the place, outside of the object/class that defines the ability
Add a LayerMask field and pass it into the OverlapSphere() call as the respective argument - it'll let you select the the layers in the inspector through a nice interface.
I'm sort of skeptical that it could be the layers, but it's worth a try. You might also throw some logs in to check if the rbs are null, and maybe use a much larger force and/or ForceMode.Impulse, particularly if these rbs have some amount of mass
Maybe share a screenshot of the inspector for one of the objects that the explosion should be affecting - particularly the rigidbody component
it keeps giving me an error when i try to have a debug message give me the rigid bodies saying cannor acess floor rb cuz it doesnt have an rb
this is the player
Are you directly controlling position or velocity in PlayerMovement?
velocity
but the layermask thing worked
i still dont get y it wasnt working without it
I do not know... I would like to understand as well ๐ค
That very much depends on how you are going to use the abilities. If an ability is only ever going to be used one way (so there will never be a new operation), then sure.
However imagine a different scenario: an ability simply contains some metadata about the ability (cooldown, how much damage it deals, mana cost, etc), but different game modes may handle the ability differently. Perhaps not even game modes, you want to transmit "player A casted ability X" across network. Now what do you do, do you put every game mode's handling code into ability classes? Do you also put the network handling code into ability classes too? Why should ability classes even need to know the fact that this game has different game modes or that it's a networked game? Now you just run into the opposite problem: ability classes suddenly need to know the every possible way an ability is going to be used in the context of the entire game.
It circles back to the expression problem again, if you go the OOP route, adding a new ability is easy, but adding a new game mode is hard; if you go the functional route, adding a new game mode is easy, but adding a new ability is hard.
sure, but the original request was "how to add more abilities easy" ๐คทโโ๏ธ
it's a decent example (well, a bit extreme), but you'd probably still not use enums and switches, you'd need a more complex approach to do game modes that affect abilities in a good way, and would depend on the specific needs for said game modes
Yes, and there are solutions to the expression problem for both directions.
The point is, there's no one simple answer to picking which approach and either comes with its own downsides. If you completely ignore the problem of adding new operations later on, then the OO approach will make adding abilities very easy, but you better hope you aren't going to add more operations later on.
The moment you need to add a new operation, your 50 ability classes will all be red and your project will not compile until you modify those 50 different files.
I completely agree with no one simple answer... ๐ I'm just saying that if you have an enum that will have more and more values (variants) by definition, that already means you need to use something that handles variants well ๐คทโโ๏ธ If you also need to handle adding more functions easily - that's another thing to consider on top of the first
https://pastebin.com/kuFkjVV3
hi, why does the enemy not get hit when the sword is close to it, but it gets hit when the sword is distanced slightly further away, and how would I fix this? thanks
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
OnTriggerEnter is really not a great way to detect attack hits like this
you should use direct physics queries
e.g. Physics.OverlapBox
will look into that, thanks
I'm trying to draw a bunch of instanced meshes to a secondary camera, but not to the main camera. The secondary camera is copied from the main camera, I set the DrawMeshInstancedIndirect call to use camera: secondaryCamera, which the documentation says should only draw to that camera, but the main camera is still drawing them. I must be missing something, anybody have clues on where I could look?
you sure your camera reference is set properly?
The docs say:
If null (default), the mesh will be drawn in all cameras
Yep, it's strange. Looking through the frame debugger and it seems like both cameras are rendering to the main render texture. I'll play around with changing that.
well that would certainly do it
Can't see that on mobile btw
well first off the first two lines where you try to set it (the stuff related to LeftControl) will be overwritten by the second two lines where you do
so effectively only the if (Input.GetKey(KeyCode.LeftShift) && canSprint) part matters
theoretically you should be toggling between 30 and 35 degree fov due to that code
which isn't that much of a difference
Good morning / afternoon/ evening depending on where you are from!
I am looking for some pointers in the right direction on how to set an external display (display 2 for simplicity) and be able to change it's resolution at runtime. I already have a list of resolutions that I can set but when I change the resolution from the dropdown only display 1 is responding and changing:
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Any settings I'm overlooking for the additional displays?
launch arguments etc
hey, can you clear for me few things about cameras? I'm using Unity 2022.3 with URP 14.0.11 and can't force my cameras to work...
firstly - I'd like to have separate cam for UI, so I have my UI camera on UI layout with UI as only layer culling and it's set to overlay.. next I have main camera as base and added UI camera stacked there... next I have canvas with image on UI layer (canvas and all it's children). Canvas is set as screen space - overlay.
So is it correct that both main and UI cam can't see it at all (preview in scene panel are empty), but still in game view canvas with image is visible? The problem is reversed if I turn canvas rendering to screen space - camera and select UI cam - UI then isn't visible anywhere (playing with distance didn't change a thing).
Hi guys I am having an issue where I cant access the variables of the child object from the parent object. Would someone please be able to help me? Here's the code https://gdl.space/qawatacawo.cs, and some screenshots of the inspector in case that helps:
floorCheck should not be of Type GameObject. It should be of Type Ground_check_script
hey, can you clear for me few things
another problem is rendering to texture and than showing it with alpha channel... so:
I have camera rendering to the texture with bg set to black, no alpha (0, 0, 0, 0) with culling mask to catch an object.. it seems to work well - I got only that object in texture and image in preview looks as it should..
Now I add it to the canvas UI as an Raw Image and it starts to be strange - my rendered image looks like it has about 50% opacity... whole image - there is no alpha and I can't even make it to show as solid (color for image is white with full alpha).
Oh my gosh, tysm I had no idea what was causing it. TYSM!
dont forget to reassign it in the inspector, when you change the type of a variable it will show Type Mismatch in the inspector
yeah I did that :). TYSM again
floorCheck.Ground_check_script.returnCount()
public GameObject floorCheck;
To this
public Ground_check_script floorCheck
I fixed the issue already, but ty for the help :)
ok
you know how you have mathf.smoothstep for smootly interpolating what tyoe of thing is there for exponentioal interpolatioinb
nvm i used animation curve and it looks worse that smoothstep
You can simply use Mathf.Lerp and apply any easing function you want.
e.g.
t += Time.deltaTime;
float eased = MyEasingFunction(t);
var result = Mathf.Lerp(start, end, eased);```
You can also use an animation curve as you mentioned:
```cs
t += Time.deltaTime;
float eased = myAnimationCurve.Evaluate(t);
var result = Mathf.Lerp(start, end, eased);```
void getDirection(){
Vector2 direction = new Vector2(playerTranform.position.x - transform.position.x, playerTranform.position.y - transform.position.y);
Debug.Log(direction);
transform.up = direction;
GameObject bullet = ObjectPool.instance.getPoolObjects();
if(bullet != null){
bullet.transform.position = muzzlePoint.position;
bullet.SetActive(true);
bullet.GetComponent<Rigidbody2D>().AddForce(direction * 5, ForceMode2D.Force); // wrong code
}
}
how can i make the bullet shoot in the direction that is calculated? that line that says wrong code, its a theory that doesnt work... so its wrong
that code is correct for shooting the bullet in the direction specified as direction
perhaps you are calculating the wrong direction
its giving errors
normalize the direction vector
you can't just have errors and not tell us lmao.
this is true and a good idea, but not the main problem
its in the editor.
I can't see your editor sir
sorry, my bad
delete using System.Numerics from the top of your script. There's no reason you should have it there
it was default
and yes you should do direction.Normalize(); right after that
what is that? can you explain in nutshel?
it normalizes the vector
oh so it normalizes all the things
add this Vector2 normalizedDirection = direction.normalized; and then apply the force based on the normalized direction
ohki thanks
actually you can just normalize the direction vector directly without creating the normalizedDirection so that is also correct
Is there a way to send a rendertexture to a material without blitting? I tried
_material.SetTexture("_PrevFrame", _prevFrameHandle.rt);
and then using a sampler2D in the shader
sampler2D _PrevFrame;
To no success
Maybe important, I'm putting this in the execute function of a render pass
is there a reason you'd like to avoid blitting?
Yes, I need two render textures in one shader
and why is blitting preventing you to do that?
public static RenderTexture Copy(this RenderTexture rt) {
var newRT = new RenderTexture(rt);
Graphics.Blit(rt, newRT);
return newRT;
}
Since if you blit you can only access the one variable you have acces to, _BlitTexture no? also, blitting executes a render pass
Blit(cmd, cameraTargetHandle, _rtHandle, _accumulateMaterial, 0);
Blit(cmd, _rtHandle, cameraTargetHandle);
Here's my HLSL:
HLSLINCLUDE
// The Blit.hlsl file provides the vertex shader (Vert),
// the input structure (Attributes), and the output structure (Varyings)
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.render-pipelines.core/Runtime/Utilities/Blit.hlsl"
sampler2D _PrevFrame;
float _Frame;
float4 _BlitTexture_TexelSize;
float4 frag (Varyings input) : SV_Target
{
float4 col = SAMPLE_TEXTURE2D(_BlitTexture, sampler_LinearClamp, input.texcoord);
float4 colPrev = tex2D(_PrevFrame, input.texcoord);
float weight = 1.0 / (_Frame + 1);
float4 accumulatedCol = saturate(colPrev * (1 - weight) + col * weight);
return accumulatedCol;
}
ENDHLSL
calls to Graphics (or other GPU APIs) don't execute anything synchronously anyway
they asynchronously queue stuff to a buffer which gets awaited on the next sync call
yeah the issue is you're blitting to the RT you would like to keep intact. Using the Copy method I posted above should do it!
Should do what exactly? make a copy of the render texture? Now how do I send that to the shader?
_material.SetTexture("_PrevFrame", RTUtils.Copy(_prevFrameHandle.rt));
RTs are still references, so if you pass the RT before it changes, the changed version will be used by the shader (-- when it does)
sry I was in the middle of grabbing coffee so excuse my low effort english xD
@ashen oyster did that work?
Er no, give me a second, maybe you're more eagle eyed than me
Here's the execute script, I put comments on the places to explain what's happening
I just get a black screen
Yes I could've used code blocks but discord's syntax highlighting is abysmal
returning just col works fine btw, that samples the blitted texture
you seem to have 4 extra blits there -- are you sure they're correct?
How do you mean?
anyway.. the issue is you're using SetGlobalTexture but _PrevFrame is not market as static (uniform in shaders)
why not material.SetTexture?
I'm talking about the accumulation stuff -- I don't really get what they're supposed to be doing lol -- just making sure you do
Ok weird, that's what I tried first but didn't work so I tried gobaltexture instead. Now that I switch back it works ๐ต
maybe you didn't explicitly press ctrl+R after your shader change -- which is needed to apply shader changes
(actually not sure about newer versions -- it is the thing I have to do in older version tho)
I'm pretty sure unity HMR that just fine since I've not needed to do that
well great that it works now then ^^
Ah yeah, they are absolutely necessary lol. They're the reason shader passes get executed at all
I have been avoiding URP/HDRP because I wanna avoid this kind of necessary magic lol.. the standard RP is just fine ๐
lmao, not for my usecases xD
pretty sure everything's a notch easier programming-wise without URP/HDRP lol
Yeah sure but then you're doing post processing with monobehaviors which is silly imo xd
I'm a fan of these SRP injections
(even though it's a massive struggle to find any good documentation on it)
well the SRP just changes the standard Update() to a specialized Execute and provides a premade and not-fully-customizable command buffer afaik -- not much of a bonus imo xD
yeah sure it can be nice in that sense -- but organization-wise a nicely named script (e.g.: Shaders/Magic/PostProcessing/FadePostProcessing.cs) might be as good
It comes down to "whatever works best" ig :P
also it doesn't have to be a MonoBehaviour if you've gone through the trouble of adding a CommandBuffer to your camera. That's actually the best practice (potentially even static method library)
im making a voxel system and i thought i should disable the mesh of a voxel if it is surrounded on all sides by solid voxels for optimization. is it necessary to do this or does the renderer not render them automatically?
Why would one need [SerializeField] when the field itself is already serialized and readable by the inspector?'
you would not
as the Serialization manual says, SerializeField just bypasses a check for the field being public. if it's already public, SerializeField doesn't do anything, as your ide might tell you
It's usually used on private fields to make them serializable and visible in the inspector. It's useless for public fields. Some people like to add useless code to make it easier to remember the code's purpose. Writing private before fields is a similar example - useless, yet people keep doing it.
Fair point; and I apparently did public out of habit instead of private
I've established some practices that I like to recommend:
- When you need it tweakable from the inspector but otherwise immutable, go for private field
[SerializeField] MyClass field; - When you need it readable from other scripts..
2a) .. but only settable within the script, go forpublic MyClass field { get; private set; }
2b) .. but only settable from the inspector, go for[field: SerializeField] public MyClass field { get; private set; } - When you need it only tweakable within the script, go for private field
this way you never really need public fields
I'm screenshotting this, if that's fine?
totally!
Thanks!
Hey guys I was trying to test something super basic and encountered a weird case which Im not sure if it existed since forver with Unity?
I have 2 GameObjects in the Scene
Object A with a Script A which has Awake and OnEnable methods just printing logs
Object B with a Script B which has Awake and OnEnable methods just printing logs
When I run this, I get logs as
Object A Awake
Object A OnEnable
Object B Awake
Object B OnEnable
As far as I remember all Awake should be called first and then OnEnable right?
It's per object
But these will all run before any Start methods will run in your scene
If you need more granularity than Start-Awake you can turn Start into a coroutine and skip frames to guarantee later execution.
Was it like this since forever?
Because as far as I remember it should run all Awake first for all loaded objects and then called OnEnable for them
I don't recall a time it was different, no
Ah okay thanks!
It has always been this way yeah
what is the website where i paste text and its on a link and i share it
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ 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.
void shootFun(){
Vector2 direction = new Vector2(playerTranform.position.x - muzzlePoint.position.x, playerTranform.position.y - muzzlePoint.position.y).normalized;
muzzlePoint.up = direction;
GameObject bullet = ObjectPool.instance.getPoolObjects();
if(bullet != null){
bullet.transform.position = muzzlePoint.position;
Debug.Log("Teleported to muzzle");
bullet.SetActive(true);
Debug.Log("Bullet is active");
bullet.GetComponent<Rigidbody2D>().AddForce(direction * 5, ForceMode2D.Force);
Debug.Log("Bullet Given boost");
}
}```
Code for bullet spawning and shooting ๐
Code for Object Pooling ๐
https://gdl.space/zuvimomive.cs
ERROR: ``` NullReferenceException: Object reference not set to an instance of an object
RANGED_manager.shootFun () (at Assets/Scripts/Enemy/RANGED_manager.cs:55)
RANGED_manager.Update () (at Assets/Scripts/Enemy/RANGED_manager.cs:26)
why cant it detect the bullet?
Error is on line 55, what's on that line?
(RANGED_manager.cs:55)
i'm going to guess that ObjectPool.instance is null since it is not assigned to anywhere in the code we've been shown
That is indeed most likely the issue, there is no singleton initialization code in ObjectPool
starts from there
i added the script to an empty object called PoolManager and referenced the bullet there
that line cannot throw that exception
that does not mean that ObjectPool.instance is not null (hint: it is)
then what should i do?
you need to assign to it. you clearly tried copying the singleton pattern without actually understanding what it is. maybe go back and look at where you copied that from and see where the instance variable is assigned
i saw a video, and it didnt explain anything like that. imma try what u said
i took it from here https://www.youtube.com/watch?v=YCHJwnmUGDk
Learn how to improve the performance of your game with object pooling in Unity!
SOCIAL
Discord: https://discord.gg/harSKuFR8U
itch.io: https://bendux.itch.io/
Twitter: https://twitter.com/bendux_studios
SUPPORT
Buy Me a Coffee: https://www.buymeacoffee.com/bendux
MUSIC
Plain Loafer by Kevin MacLeod
Link: https://incompetech.filmmusic.io...
yeah you 100% missed the part where they assigned to instance
what part is it?
my guy, it is a 4 minute long video. go watch it yourself
where they defined ``` public static ObjectPool instance;
please actually pay attention to the video
then surely you saw where instance was assigned
cuz its correct code to code
no it isn't
after fixing its giving me error on line 55 and 26
that is the whole enemy shooting and moving code
clear your console, make sure your code is actually saved and has compiled, then do whatever it is that causes the errors. because line 55 cannot throw an error
oo it was a completely different script that was just a test
forgot to delete it
it showed me the actual script when double clicking at the first time, ig i must have clicked a different message
I am looking at the URP samples. it gives an error in its initial form.
Error (active) CS0434 The namespace 'Samples' in 'Samples.GameplaySequence, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with the type 'Samples' in 'Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' Assembly-CSharp-Editor P:\UnityProjects\Samples\AnimSamples\Assets\Samples\Shader Graph\14.0.11\Production Ready Shaders\SRPCommon\Scripts\Editor\SamplesShowcaseEditor.cs 94
In my infinite inexperience, i tried to move things to a namespace ShaderSamplesShowcase which causes:
Error (active) CS8773 Feature 'file-scoped namespace' is not available in C# 9.0. Please use language version 10.0 or greater.
IDK what to do
show how you tried to add the namespace
namespace ShaderSampleShowcase; under the using references
you cannot use file-scoped namespaces in unity. it has to be a block scoped namespace
Ok thanks, i just put it in {}, but the errors remain (Not the namespace error, the initial one)
well you've got a type with the same name as a namespace. did you put that type into the namespace you created?
or have you considered simply renaming either of them?
I believe so. the namespace block encompasses everything except the using statements. I attempted to rename samples as the first thing i did, but it says i cannot.
you have to rename it from the class declaration, you cannot rename it from there
I am having trouble tracing that back. where i thought it was, it is not. i will keep looking. Thanks
wdym? did you not put that class into a namespace?
I thought i did. I am off to take some c# courses. Thanks for the directives ๐
Hello, currently I work on a Tycoon and I struggle a bit with inability to choose way to store sprites of each building from blueprints. With my current knowledge I guess that the most optimal solution would be to use the SerializeField attribute but it may be you know better way to do that : pp
I'm not sure if I understand your problem correctly.
Adding serialized fields in objects directly makes it easier to configure your assets in the Inspector. The drawback is that sometimes you end up with storing the same information in multiple objects. Usually it doesn't hurt, but it could be a problem if you have thousands of instances of that object. In such cases, it's worth considering if it's possible to store it in some sort of singleton or manager. But in 99% of cases [SerializeField] is good enough.
either put your world space camera there, or you'll need to manually raycast against that object and convert the hit point to a point relative to the canvas
I'd like to bump poor soul's problem =p
Anyone here good with Quaternions, the following code is for rotating my player but it's a little clunkier than I'd like, I want to know how I can rotate on the Y-axis at a different speed than on the x and z axes. Y axis rotation is for the players movement rotations whereas X and Z are for aligning with the ground normal
if (vector == Vector3.zero)
{
rb.MoveRotation(Quaternion.Slerp(transform.rotation, lastTargetRotation, rotationSpeed * Time.fixedDeltaTime));
return;
}
Vector3 forwardDirection = Vector3.ProjectOnPlane(moveVector.normalized, targetNormal);
Vector3 upDirection = targetNormal;
targetRotation = Quaternion.LookRotation(forwardDirection, upDirection);
lastTargetRotation = targetRotation;
var horizontalRotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.fixedDeltaTime);
rb.MoveRotation(horizontalRotation);```
Friendly reminder to set your render texture precision higher, I've been debugging for 6 hours only to find i set the descriptor to default instead of ARGBFloat.
All my issues were fixed after that :<
nvm I realized the value was in the editor, not in the script
Hello, i wanna ask a question about AudioClip in Unity.
When i try to GetData() from AudioClip that i load from path using UnityWebRequest it give me error: "Cannot get data on compressed samples for audio clip "". Changing the load type to DecompressOnLoad on the audio clip will fix this." But when i open the file from UnityWebRequest i have enable compress and stream to false. Does anybody know how to fix this?
@open dome do you download it from the internet? or load a file from your Assets folder?
I load the audiofile from my local device.
hmm it should be plug & play
@open dome why not UnityWebRequestMultimedia.GetAudioClip?
getting data isn't necessary before you create an AudioClip out of your downloaded audio
Yes, i already use UnityWebRequestMultimedia.GetAudioClip but it still give me "Cannot get data on compressed samples for audio clip "". Changing the load type to DecompressOnLoad on the audio clip will fix this." Error.
audio clip ""?
can you try using var clip = DownloadHandlerAudioClip.GetContent(www); as in the docs?
also you check if it's done but if it's not you just skip -- your function is not very robust for non-local files
GetContent I think is synchronous, so potentially not ideal for online files either, but you'll get around it with isDone similar to how you did (while (!isDone) { yield return null; })
When i change the way to get the content using var clip = DownloadHandlerAudioClip.GetContent(www); its still give me error when trying to GetData() from the clip.
but it can play properly if you don't try to GetData, right?
Yes the clip before and after changing the way to get the clip can play properly.
But i still can't use the GetData function from the clip.
I need the clip to be able to use GetData function, since the whisper plugin that i use require the access on that function.
I'm wondering whether at some point these are overriden
might wanna try it before GetContent?
also yeah sounds like your previous method should work too but Unity is weird in some cases when it comes to following the docs xD
looks like a weird execution order thing by unity's side imo
you might also wanna try waiting a frame or two after the download is done
@open dome or clip.LoadAudioData()
Putting it before GetContent Still giving error
surely Unity side bug since GetData should automatically load/decompress it -- but yeah.. dlHandler is instructed to not even compress it in the first place
When i try adding wait for 0.2 second it also still cant use the getdata function
darn
this might work
I've had my share of frustrations with unity web requests -- to the point I just went with .NET's HttpClient eventually xD
once I have the MP3 or whatever it's just easy to load it as an AudioFile -- same to transporting it to any other formats
it worked!? I knew it!
Hmm... where should i put this function?
When i Debug.Logging the function it return True. But still can't use the GetData function from audioclip
nope :<
the 0.2sec should be done AFTER GetContent
also, the BUT was to change a setting in preferences, but seems it doesn't exist ๐
insert the wait right above GetData
also, mind that GetContent is kind of synchronous and indeed expects dlHandler to be done
more robust is while (!www.downloadHandler.isDone) { yield return null; } (wait until it's done before proceeding with using the downloaded file)
Still giving error when trying to GetData from clip after waiting.
go with different plugin, then, imo ๐
If you're willing to run your own local whisper model (assuming you already do), could take a look at LlamaSharp
-- I've made an example for Whisper integration with it as well: https://github.com/SciSharp/LLamaSharp/pull/656
it's for speech-chat so it might look a little complex but the transcription part is much easier -- and it can serve as a server as well
(sorry I can't help with the actual issue you're having ๐ I've exhausted all my ideas -- maybe someone else has more)
Its ok, thanks for the help.
oh I meant to link whisper.net btw: https://github.com/sandrohanea/whisper.net -- but the code should be the same as the LLamaSharp example shows
Code : https://gdl.space/lazuyugilo.cs
Problem : the bullet is not shooting correctly, what could be the problem? please help
sorry, i was not ignoring you at all. I has just walked away to do something, and when i came back, @somber nacelle had picked up the conversation
please mention me if replying
Hi!
I've been banging my on this for a while, I smell some gotcha regarding articulation bodies, but I couldn't really find anything specific to them.
I can use rigidBody + Joints for this, but there is some other system that works with ABs nicely that I am trying to hook into, so I want to give it a good try before I change away from ABs.
Goal: Generate a string of objects (rope) given length etc. as public params to the root of the rope at start.
Observable problem: Child ropes are created at the given local position, but they snap to global coordinates through the AB on them, as if they were spawned as root, and then simply moved without the teleport method. (I did try teleporting the child too, got the error "this aint root" as I should.)
Annoyingly, the first child (the one connected to the root, R-c1) works as expected: it spawns SegmentLength away and stays connected. Every other child behaves as if its the first child...
Related bit of code:
// File and object: RopeLink.cs
void SpawnChild(int remainingSegments)
{
if(remainingSegments < 1) return;
childRope = Instantiate(RopeLinkPrefab);
childRope.transform.SetParent(this.transform);
childRope.transform.localPosition = new Vector3(0, 0, SegmentLength);
childRope.name = $"RopeLink_{remainingSegments}";
var rl = childRope.GetComponent<RopeLink>();
rl.Root = false;
Debug.Log($"I am {transform.name} and i spawned {childRope.name}");
rl.SpawnChild(remainingSegments-1);
}
void Start()
{
if(!Root) return; // dont spawn stuff if youre not the root
SpawnChild(numSegments-1);
}
RopeLinkPrefab is set.
I have tried using Instantiate with the transform and parent parameters too, exactly the same behaviour.
Doing this manually in the editor works 10/10.
What am I missing about ABs and instantiating them here?
Answer: use rb.velocity = direction * bulletSpeed instead of rb.AddForce
so that would fix the direction?
facingLeft/facingRight is irrelevant since the direction is always facing the player
it will fix both speed and direction yes
oh yeh
thanks
you're welcome
hi, TLDR sorry ๐
can i add * Time.deltaTime so that the fps wont matter?
or it wouldnt work as supposed?
no, adding * Time.deltaTime is wrong
you're setting the velocity of the object, which is u = x/t -- includes dT already when translating to movement units
imma send u a video, a really funny bug ๐
I like videos
poor cow lol
do i just make it trigger?
idk what you want -- but yeah how bullets interact with the world is an entirely separate system -- implement based on your design
I wouldn't mind the knockback in a game I was making -- I kind of dig it
the cow is the main character ๐
i will make it for a tank enemy, but how can i reduce the knockback?
make it explicit instead of letting the physics system handle it
explicit as in code specific AddForce event on impact
i dont understand
Yup, I was just unsure if using SerializeField would be the best way to store my assets (for example those like sprite of each building) and if there are any other optimal ways to do that. Thank you a lot ๐
so when the bullet hits the cow, the cow exerts force to the bullet to cancel out the force?
alright, so yeah first step make it trigger (if you want), then add an OnTriggerEnter2D(..) { cow.AddForce(dir * knockbackForce)
Ooo ohki, thanks
but that requires Cow to use force instead of velocity/transform for movement as well
also rate my game design in #1265185860966682684 too please
nah sry my mind ain't focused enough now for non-plain-code stuff xD still having coffee
its directly changing velocity just like we used in the bullet
๐
if the Cow uses velocity, you go into custom physics territory -- like coroutine with knockback
๐ญ nvm, lets wait for the tank enemy's turn
Hello
I have a problem in input when i enter playmode the input names changes but the movement no
but when i change the inputs in the play mode it become fixed
how can i fix that?
Potentially something like this:
IEnumerator Knockback(GameObject bullet, float knockbackForce) { // Called from the TakeDamage(bullet)
Vector2 dir = bullet.transform.position - cow.transform.position;
float t = 0;
while (t < 0.25f) {
t += Time.deltaTime;
cow.rb.velocity = -1 * dir * knockbackForce;
yield return null;
}
}
nice font! Which one is it?
what? ๐
it`s a personal font to make my game not the same with any game
but the font doesn't look like that i change some things in the inspector
oh you created a font just for your game? cool
no but i changed on a internet font to look like that
then can you help me in the problem please sad_cat
is there any way to not give knockback without using trigger? just asking
your question doesn't make much sense btw ๐ I've read it 3 times now still don't know what the issue is or what you want to fix
i thkink is a unity glitch
did u try to build it and see ?
it'll always be buggy unless you handle it with a single system (either built-in physics or custom physics)
no i tested it from the play mode first
but i will try
i wouldnt really go with this approach tbh, its very reliant on the bullet still existing and directly setting the velocity of another rb is gonna be annoying for debugging later. Something like this could just be done by keeping track of what the knockback force was and then the rb itself applies these changes
yeh cuz i used addforce for my jetpack. it worked in the editor but not in the build ( android build )
you handle cow movement with velocity but non-trigger bullets apply force and depenetrate (depenetration likely causes the knockback you see)
i will try
so it's buggy atm, but bugs can make nice features lol
yeh, that gave me an idea for a new enemy
was trying to simplify because of this :p
but yeah needs much more work for a proper custom knockback feature
To clarify, whenever you declare a field, it stores its content if it's a struct and stores the reference to content if it's a class. For example: when you serialize an int field, it stores its content, because int is a struct, but if you serialize Sprite field, it will only serialize reference to that Sprite, because it's a class. The reference usually takes only 12 byte of space. Also: multiple fields can refer to the same class, but can't do that with struct, they will just copy its content.
yeh maybe i will just stick to not making the bug into feature
it's a pretty cool feature tho just saying ๐
game would look much less "alive" if it flashed instead of getting knocked back
def adding to the list
but here is the thing, when there are like 10-12 enemies during boss fights, thats just a nightmare for the player
but, can be a good game design feature ๐
where do you get this 'The reference usually takes only 1 byte of space' ?
did`nt work
i can anyone help me ?
I think I just memorized it wrong. Looked it up, turns out it takes 12 bytes in .net. Correct me if I'm mistaken.
12 bytes is correct. 1 byte would mean a maximum of 256 references which would be silly to say the least
What's your manner of doing movement in your 2D games
Usually did a rb.velocity for player and such but just learnt about transform.translate
Was wondering if there were any others
!csds
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Relative to Start and Awake, Awake would always occur and comes first whereas Start will occur after Awake and only if the object is active/enabled iirc
Start is called on the frame when a script is enabled just before any of the Update methods are called the first time. Like the Awake function, Start is called exactly once in the lifetime of the script. However, Awake is called when the script object is initialised, regardless of whether or not the script is enabled.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html
for Unity Monobehaviours you cannot use a constructor
if it's a POCO, yes but then Start and Awake do not apply
Thus why I had assumed they would want to be redirected to the c sharp discord server for clarification - solely with the c sharp content.
any help here?#๐ปโcode-beginner message
will you please stop acting like an overentitled child
and can you stop acting like a dad
listen, this server has rules, follow them or get told off
perhaps you would prefer to hear it from a <@&502884371011731486>
We have a no crossposting rules. Please don't, thanks.
okay
hi not sure where this goes but Visual Studio intellisense does not show be comments above functions/properties - can I enable?
Maybe show an image to illustrate what you're seeing versus what you'd expect to see - I'm assuming you've seen a different image elsewhere with some proper "comments".
ah, if you do a full xml comment with <summary> tags it seems to work. I was taking shortcuts and omitting the tags, which is ok for documentation generation, but apparently not here...
type 3 / to get this autocompleted
I know but it was overloading my clean code with comments! I turned it off. I can at least edit to 1 line I suppose. Doxygen will grab any comment, unfortuantely visual studio seems not to and wants the specific summary in case there is further info
I know but it was overloading my clean code with comments!
I don't get this.. comments only exist that you add ๐ค
so by default typing /// adds multiple lines of comment with 3 for summary, plus all parameters. Yes you can edit after but... This can hugely increase length of code to scroll through... that is all. If there was a /// add 1 line summary add-on it would be nice...
generally I wants comments - but small 1 line ones
This isn't specific to Unity. You'll probably get better feedback in !csds
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Are async methods ran on a different thread?
No
I am reading that they โdont block the main threadโ but coroutines do. What exactly does this mean?
I'd say they're quite similar...
async is a bit of a mystery - you don't see it much in Unity code! But I see it much like coroutines. Coroutines delay the running of code until later and/or await the end of something. Nothing is multithreaded which is odd!
You could run functions on other threads and wait for them using async-await... but that's not very common in Unity
the docs talk on Coroutines: "yield: The coroutine will continue after all Update functions have been called on the next frame." In other words you are adding an immediate delay in the code to run the coroutine! But if the couroutine then yields for time or for an htttp call it makes sense...
which as @little meadow says is like async
Is it common to even use more than one thread usually
Depends on the perspective... Unity does it all the time, it's just that Mono's code is kinda limited to one thread...
I usually use job system for that.
Ok interesting
you can use threads, but not access the Unity API in them, so limited...
this is what i see
Unity does support milti-threading. it is only WebGL builds that do not
i am surprised there isnt an easy way to multithread by now
plus the engine itself is threaded (except sad webgl)
just not the 'main' thread
rendering etc
Sometimes it's nice having such concept hidden behind a "complex" door. it prevents people not fully grasping the idea to use it i guess
ยฏ_(ใ)_/ยฏ
I feel like multithreading wouldn't be safe if it was easier. I think it's difficult mostly to prevent potential issues.
I think the forums would be fullup double if Unity was all fully threaded - not having done it myself there will be many gotchas to making things thread safe - I know that much
I think there was talk of doing it in a way that would be safer. Does DOTs not allow this now?
Regular C# threading has (always?) been available.
Unity has a Job system to make threading easier and safer https://docs.unity3d.com/Manual/JobSystemOverview.html
Swag thanks
ah that would be it. Of course they had to make their own system adding more change from core C#! But in this case may be in a useful way
Instead of relying on portable, high performance, safely multithreading C# in 2018 era of Unity? ๐
what changed in 2018? But yeah I should try it out one day - too much to do! Looks like may compile down to great C++ too with native arrays
That's when the Job system (and early versions of a lot of DOTS initiatives) launched, which was during a time where C# was moving a lot slower.
I want to create a Third Person Shooter character using the Unity "Animation Rigging" system. Is there a source for this?
yes did you look it up ? so many examples esp on google
Yes, github projects etc. I looked but couldn't find a clean project. Do you know of any clean project related to this?
nah I build things, I don't grab random projects to start from
Actually, I got to a point on my own, but I'm having problems with aiming, do you have any ideas on how to solve this?
maybe. how should I know how to solve somethin you haven't explained yet
looks fine to me
he just chill like that
the twisting is normal , you probably havent unchecked one of the axis (forgot which one, I think Z?)
under settings iirc
I remember that I had removed the z axis, so I deleted this project when I couldn't fix it last time ๐ Now I will try again with a new project.
๐ ๐
also another way I like to solve the looking behind with IK issue is adding a dot product or similar method to find out if I'm "twisting" too much compared to my character forward direction and rid of the "Weight" of ik
I tried removing the other axes as well, nothing changed. I think the problem was due to the character
only needed to remove 1, the rest are fine.
Im creating a game template that i can use for any future game, any tips on how to make a save/load manager ? im thinking about how to make it as easy as possible for new components to become saveable and loadable with the manager doing all the heavy lifting... I know that i have to use an interface for the Isaveale and probably keep track of them all in the saveManager but im not really sure... do any of you have any experience with that?
By the way, there is something I want to ask. How exactly should I track the aim point of the gun? I created an object and made it the child of the camera. Is there a better way than this or is this a good way?
I have interface as well for anything I want to be ISaveable
maybe check for relative rotation and start turning the whole character around before he becomes spine twisting?M
yea thats a nobrainer but did you manage to make it easy for new saveables be simple to implement?
i was thinking about having a structure like
SaveManager -> GameData -> ISaveables
so that i can call from anywhere a game load/save and affect the ISaveable when i need it
but not sure if it just doesnt complicate it for no reason
yeah I make all my Saveables register themselves to the savemanager
not typically. Unless maybe I'm carrying DDOL or a Canvas
you can still do it across scenes as long as the manager has an easy way to be accessed. Singleton helps with that
since cross-scene referencing don't work
not my code but I wanted to filter a certain element, any way to do that? (it's just a panel with a centered render texture image
loop through the results
What is their type? What do I checkM
The docs are missing info
RaycastResult. It says it right there
from there grab whatever component /gameobject you want
idealy you need something to make it distinguished from others if you have multiple of same components
THE PLAYER DONT GO TO ANOTHER CHECKPOINT IS THIS SCRIPT RIGHT?
using UnityEngine;
using UnityEngine.AI;
public class NavMESH : MonoBehaviour
{
public Transform[] waypoints; // Array of waypoints to visit
NavMeshAgent agent;
int waypointIndex; // Current waypoint index
Vector3 target; // Target position for the agent
void Start()
{
agent = GetComponent<NavMeshAgent>();
// Start at the first waypoint
UpdateDestination(); // Set the initial destination
}
void Update()
{
// Check if the agent is close enough to the target
if (Vector3.Distance(transform.position, target) < 1f)
{
// Get the next waypoint
WaypointIndex();
// Update the destination to the next waypoint
UpdateDestination();
}
}
void UpdateDestination()
{
if (waypoints.Length > 0) // Check if waypoints array is not empty
{
target = waypoints[waypointIndex].position;
agent.SetDestination(target);
}
}
void WaypointIndex()
{
waypointIndex++;
if (waypointIndex >= waypoints.Length) // Wrap around to the first waypoint
{
waypointIndex = 0;
}
}
}
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ 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.
post the code properly its hard to read on mobile. Read linked instructions above
fuckin hell..
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
send the link
it's honestly impressive how bad some people are at following simple instructions
whats the simplest way to prevent more than one scriptable object of a type being created
in my case i have an item database scriptable object, so there should not be two of these assets in the project
need to make sure if that happens i can throw an error or something
you could put some code inside of Reset that checks the asset database for another object of that type. of course you'd then also have to wrap that in preprocessor directives. or you could go the even more cursed route and make it a singleton
hmm i see i wonder why theres no built in attribute to prevent more than one
unless i should not use a scriptable object
why do you care about it being one though? having multiple can be useful for testing things and whatnot, plus usually you don't accidentally make more, and even if you do, they shouldn't break things
Sounds like you're describing the Singleton pattern there
yeh but its scene specific where as singletons are around for most of the application
I don't think so.
Create your own class, derived from PropertyAttribute.
Create a CustomPropertyDrawer, derived from PropertyDrawer, for this class.
In a static method with the InitializeOnLoadMethod attribute, enumerate through the Assets with the AssetDabase.FindAssets method and find whether there is any other object of the desired type found.
wait... so you have different SO class for each scene?
different instances of the database
so... you do want more than one... I am confused
Is this pattern also applied to assets?
oh sorry i even confused myself there lol. no there is only one SO asset file but it exists for specific scenes that load from it but not all scenes need it so its not loaded in for those scenes (addressable situation)
for example i dont need it on the main menu
Well, if it's not about creation in assets, use a singleton pattern, as previously mentioned
ah, okay... so... I'd generally just ignore this and just not make more instances ๐ unless it makes you really sad... in which case you can always make an something-something-asset-processor, which tells you "hey, these new assets were added" and you can then go through them, detect that some of them are not what you want and show the user a message "how about I delete those, huh?!" and then no matter what they pick - you delete them anyway to assert dominance!
can that still work with addressables
Haven't worked with them, but they only make your assets accessable. How can it interfere with your singleton pattern?
https://docs.unity.cn/2017.4/Documentation/ScriptReference/AssetPostprocessor.OnPostprocessAllAssets.html I think you can use this one to detect when a new asset thingy is created (there might be a nicer method to override though)
is there a way to get a specific peice of data from a json?
could use newtonsoft to read the file and then access the key directly
newtonsoft?
Subclass or Dictionary?... that's the riddle! ๐ค
Is it a subclass costly and heavy to store datas on the fly when you have about of 10/15 objects that interact with a trigger every ... mmm... 15/30 seconds?
unity doesn't support reading specific parts of json natievly? eh ill install it, thx!
it doens't appear in the unity package manager
I have to manage a spaceship traffic, and I need to store about 5 or more different datas, so I was planning to use a List ... but a dictionary would be be |_____________ o _______________/ that long
So ... I was thinking about a subclass with a bunch of parameters.. it's easy to store it and also less chance to mess us with value ๐
where is it?
Yea, why not.. why I shouldn't use a subclass I like it so much in the end ๐
don't you think are nice? ๐
You can install it by name, com.unity.nuget.newtonsoft-json
See the trigger?
when the ships enter on the right side of the trigger I have to store
Class of the ship.
steering value
engine speed
if it's player or not
fuel
agent which is driving the ship.
So I guess to make a subclass with all of that parameters could be a nice idea, so I will store the subclass in a List for all the ships that use the tunnel
๐ค Could be better than a dictionary... I guess.
Dictionary has a key and a value, the value can be simple, an int, or a complex set of data in a struct or class
this error happens when i press on select player mask in inspector
this my code
oh ok sorry
and READ the error messages, it's pretty obvious that they are NOT coming from your code
I have an egg falling (in the direction of rocks) and you can control it right and left using its rigidbody in x axis, i want to know how can i increase its fall speed by code overtime, lowering mass and drag didnt work
mass does not mean anything in context of falling speed. You simply multiply the gravity by some const or whatever value you want
i cant access the gravity values from the rigidbody? Do i need to change the gravity value from setting for the whole project?
yes if its only for a specific object you just add onto it via velocity/addforce
making it inconvienet for someone to help you is the best way not to get help..
Here
this is wrong btw waypointIndex >= waypoints.Length
you always -1 the length for indexes
oh
as collections start from 0 index
10 items index can only go up to 9 etc.
did you debug what the index is when it stops working
yea
ok..so what is happening
I don't have eyes on your project, by the code alone I cannot know if its wrong
it always stops in the 3rd checkpoint
alright so that would be index 2?
wdym each checkpoint 3 times? you mean it does all of them in array 3 times or you mean it only does the first 3
can you show where all the waypoints are placed
if i move the thing it goes the same checkpoint it stopped
so the index is still there at 2 ?
also what is the stopping distance of agent? is it less than 1 at least
its 0
alr can you record a short vid of whats happening with the agents inpsector visible
ok sure
not really seeing anything in the code that would stop it so early
Any way u can elaborate on this im a little slow I dont see the vision
Hey guys, the Packages folder should be in the gitignore... right? For some reason it's not in the gitignore.
https://github.com/github/gitignore/blob/main/Unity.gitignore
no it should not
what do you want to know ? I myself try different methodologies
wait hold on it contains the manifest.... ok I guess "ProjectData~" inside of Packages should be in gitignore?
Like how do you go from just implementing an interface to it getting autosaved
Like for me I have to add my saveable stuff to the โPlayerDataโ before it saves
many large files inside of this "ProjectData~" folder
should I ignore Packages/package/ProjectData~/ or Packages/package/?
Also another thing the classes have to be serializable right that works with the interface too?
no idea what that is
Must be something new in Unity 6 or some package I installed did this.
look skip forward a little bit
because the first time i recorded it i messed something up, skip forward when i play it again
ahhh @knotty sun I know what did it, Unity Visual Scripting. For some reason it initialized on my brand new project. It is something that needs to be ignored.
ohh ok I see
at 0:58
yes
My saving Class takes in Generics so I can pass whatever data I want
each ISaveable has their own Data they save to
U dont have [Serializeable] on the interface tho right
somesave to GameData, other PlayerData etc.
no
Debug.log the Distance check and see whats going on there, start by trial and error
Wait what does it take in if the interface has Aa save method (im guessing)
the only thing that knows about the interface is the Save manager
Whatt
yes they each send their own struct/class to save in the final class that actually writes to file/cloud or whatever
I can give you a basic example but I'm not at my workstation rn. I have easier time showing than explaining lol
Any example would be helpful lol
Are you talking about a list of ISaveables
But then you would need to tell the objects they are isaveable
the interface is in place to run specific method on all of them. or grab a specific item/struct
like .Save method lets say
Yeah i think thats the confusing part
But the objects arent ISaveable?
How do they call that method then
the save manager
an event usually starts the whole thing for me
I would like to code my own SDK for users to upload their own custom avatars in my game, does anyone know where I can learn this?
it ended on waypoint 4
The save manager is calling the interface method?
print the distance i meant
like what waypoint its aT?