#archived-code-general
1 messages · Page 250 of 1
you can use unity's mesh library externaly?
yeah no, my issue is related to binding textures to image units, how does that work in unity?
Are you talking about shaders specifically?
Most done through HLSL
which is kinda like GLSL, though Unity's got a lot of their own methods in place
yes how do you write to a texture in hlsl?
thanks looks pretty cool
and if you know how it works conceptionally then you've also have ShaderGraph which is more node based
hlsl shaders look like like json
hey guys. i used unity's integrated version control in one of my projects and now all of my projects have these green icons telling me to "check-in" the changes. is it possible to disable it in some projects and enable it in others? also i have a lot of archived projects in unity cloud. is there a way to delete those? (second picture)
Ask both questions in #💻┃unity-talk as they're not code questions
I moved the scripts of my game into a folder called scripts. I didnt change a single word in any of them. Now every single script with an Action is telling me it needs to be of type delegate. All namespaces are in folders with the coordinating name. I tried moving them all back to the assets folder and the error wont go. Is something wrong with the Assembly Definitions or something?
Did you name your own class Action? It might be picking up that one instead of System.Action as it's "farther" compared to the stuff you put in the global namespace
Omg.................................... Thats LITERALLY what happened. THANK YOU!
What you can do is try to navigate to the definition of that class, if you ever have these kinds of errors in the future. Ctrl+Click the Action for example, and it'll take you to where it's declared. Ensure it's where you expect!
Wow! That is great advice. I kept clicking the definition for the different delegates themselves but not Action since it wasnt underlined. I should always check the class first!
How do I get a list of scriptable objects from a path? I'm trying everythings but I can't get it to work...
For what reason? Is this for an editor tool?
yes
Then #↕️┃editor-extensions and use the AssetDatabase.FindAssets function
I'm struggling to find Settings Manager in my package manager. (https://docs.unity3d.com/Packages/com.unity.settings-manager@2.0/manual/index.html). Is there some way to get this that I'm doing wrong?
It's supposed to be in the namespace UnityEditor.SettingsManagement;
Look in the Packages folder, is it already there?
no
I can get the package by adding a different package that adds it as a dependency. But right now i'm trying to edit that package, because it has a typo
Or just add it via name
umm guys, i just installed unity 2019.4 on windows 7 and its not opening What should i do?
this is a code channel
Hey, I'm trying to have multiple SOs inheriting from a generic SO, each storing a Value of the type. When I want to have a field of the base SO class and create it as one of its inheriting classes, that doesn't work because I need to specify the generic in the field declaration... What do I do?
private ValueBase value; // needs generic like ValueBase<int>
if(...) value = new IntValue();
else if(...) value = new BoolValue(); // doesn't work if i declare value as type ValueBase<int>
value.ValueName = "someName";
I tried making the ValueBase<T> implement an interface, but when I declare the value as type of that interface, it doesn't let me access the fields of value anymore, as the interface doesn't have those fields...
You want one value can hold different types?
in that situation, I make a non-generic abstract base class that the generic inherits from
but then I can't access the fields of type T in it, can I?
expample:
public abstract class FixedSpawnpointBase {}
public abstract class FixedSpawnpointBase<T> : FixedSpawnpointBase {}
public class FixedSpawnpointSingle : FixedSpawnpointBase<TilePlacementSingle> {}
public class FixedSpawnpointLine : FixedSpawnpointBase<TilePlacementLine> {}
correct
i need to do that tho :/
well how are you going to do that without knowing what type it is
I wanted a switch statement to set it as the new type
that is bad. don't do that
switch (valueType)
{
case ValueTypes.Int:
GlobalIntValue intValue = new GlobalIntValue();
break;
}
value.Name = "";
the classes are Scriptable Objects and I want to create one in the editor whilst deciding its type there
why are they generic on value types that you don't define
You can use a enum and pointer to have a fixed size allocations first, but finally you will find that you are reimplementing a compiler
when I do this sort of thing, the generic argument is one of my classes, so I slap an interface on that shit
public abstract class GlobalValueBase<T> : ScriptableObject
{
public string Name;
public T Value;
}
public class GlobalIntValue : GlobalValueBase<int>
{
}
thats what I was doing
if(valueType == ValueType.Int) value = new IntValue();
and then access it's parameters
what are these different types for T
string, int, bool, float, later maybe classes too
ok, that makes zero sense to try to store on a single variable
See, reimplementing compiler
well shit
yeah dude. what you are trying to do is just dumb
there is a smarter way to structure your code, that doesn't involve any of this
..... no
you need to ask yourself WHY are you trying to store the same one variable, but with so many types that have nothing to do with each other
I mean, there's a button below that then creates the ScriptableObject of the type
ok
WHY do you need a base SO where all these random types are on the same variable
WHY
they all store a value. thats the common base
to group them in a list
make a generic data entry
if you want to store all of these, then I would make a separate little container class that does different things depending on its contents
I just don't see how you can actually use all of this in a way that makes sense.
can u pls give me some pseudo code? I don't really follow
I'm working on a save data thing with a similar thing, but the way that works is that my code just acts on an ISaveData interface to call .Load(), and the inner logic takes care of the rest
I want to have a ton of SOs each storing a value. Also they should be shown all together in a list.
thats cool too
then i cant store it in a list
they don't need to all be one variable that can take on every type
sure you can. don't make any of this generic
u mean like
switch (valueType)
{
case ValueTypes.Int:
GlobalIntValue intValue = new GlobalIntValue();
intValue.Name = valueName;
intValue.Category = category;
AssetDatabase.CreateAsset(intValue, SO_PATH + GLOBAL_VALUES + "/" + valueName + ".asset");
AssetDatabase.SaveAssets();
break;
case ValueTypes.Bool:
GlobalBoolValue boolValue = new GlobalBoolValue();
boolValue.Name = valueName;
boolValue.Category = category;
AssetDatabase.CreateAsset(boolValue, SO_PATH + GLOBAL_VALUES + "/" + valueName + ".asset");
AssetDatabase.SaveAssets();
break;
case ValueTypes.Float:
GlobalFloatValue floatValue = new GlobalFloatValue();
floatValue.Name = valueName;
floatValue.Category = category;
AssetDatabase.CreateAsset(floatValue, SO_PATH + GLOBAL_VALUES + "/" + valueName + ".asset");
AssetDatabase.SaveAssets();
break;
case ValueTypes.String:
GlobalStringValue stringValue = new GlobalStringValue();
stringValue.Name = valueName;
stringValue.Category = category;
AssetDatabase.CreateAsset(stringValue, SO_PATH + GLOBAL_VALUES + "/" + valueName + ".asset");
AssetDatabase.SaveAssets();
break;
}
public interface ISaveData {
/// <summary>Parse the information in this instance, and apply it to the game world..</summary>
public void Load();
}
/// <summary>Interface for something that makes ISaveData on request. </summary>
public interface IDataSaver<out TSaveData> where TSaveData : ISaveData {
/// <summary>Create a save data based on the current state of the world.</summary>
public TSaveData MakeSave();
/// <summary>When there is no data, do this to the level when we load.</summary>
public void LoadDefault();
}```
whatever god you believe in will smite you if you put this in your code
true, thats what I'm trying to avoid here xD
as in, not inherit from the generic base class?
true
this is not the work of a sane man
this is cancer
stop it
that's what the generics did to me
I'm trying to write some expandable code here, but that shit fs me over
how can I then tho store them in one list?
do I just make the list of type object or smth?
make an interface. treat them differently, because they are clearly not the same
You need to do this if you want to store different type and dynamic cast them (ie you need something to runtime determine their type), and dont that if you can
other than the generic they are TwT
I just don't understand how a class can hold a string vs int vs float and "maybe some other types later", and that these classes are all so similar that they should be treated as one generic
you're probably right
they are too different. so treat them differently
how do I approach this?
public interface IGlobalValue
{
public object Value { get; set; }
}
you could successfully store the value of a different type, sure. But then how the hell is the rest of your code going to interact with that class without having its own giant switch case nonsense again.... every time it wants to do anything with the contents
look at this, you see why this works?
because my Load() function has no type-specific anything, so its interface does not either
I see
If you really want to store dynamic type, look at any dynamic type language interpreter eg python to learn ( i didnt read cpython source code btw)
so I will make my interface without any contents I guess?
then the objects that create savedata ARE generic, with an out T, so they can just out an object that implements a given interface
I think that'll be too much
if I use an interface I wont have any way of accessing their fields tho too, right?
and then I need to resort to giant switch statement again...
Don't know the full context, but are you looking for something like this?
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching
I to recommend the "new" way to do switches, which is way less verbose.
Why not just use polymorphism?
I don't know the whole context. Only seen the switch block code that you shared, but it can be compressed down to one line probably. With the implementation for each type defined within the type.
that might be a good idea, I'll see if it works tmrw.
True. Too much repeated code.
how so?
interfaceInatance.DoItsThing()
so I add a method for creating the scriptable object to the interface and implement that in each of the inheriting classes?
where can I find out about that?
On the link I sent
oh sry
There is a better one
You can differentiate both switches knowing that the "regular" one is a switch statement, while the new is a switch expression.
i see, looks really interesting
Yes
You can also have a base class that does the repetitive work.
regarding this, I don't know how it helps me tbh. Or am I looking at the wrong aspect?
if(value is GlobalValueBase<>) // now I need to specifiy the generic again
{
}
tldr;
I want SOs holding a value of different types, so I can store all global values for my game. I'm having trouble structuring the code so I can compare SOs values in the editor to form conditions and also want them to be all in one list, so I can have a good overview in the inspector.
I would do something like
Then
Obviously something better than that, but you get the picture
what's the "where T : struct" for?
i see :)
In this case I only accept structs
He wants his generic to be all types (class and struct)
Then don't use where
im working on an inventory system in unity, which right now is being save in a Dictionary
//int is the index in the hotbar
Dictionary<int, ItemScrOBJ>
My problem is that I want to added an item count, as a separate int var. What would be a good way to implement this new var. I was thinking
Dictionary<int, Dictionary<ItemScrOBJ, int>>
but I'm not sure if its a good implementation
Make a wrapper for your ItemScrOBJ that references the ItemScrOBJ and has a count field.
Any ideas why my Grid would be off like this ?
void Update()
{
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
mousePosGrid = theGid.WorldToCell(mousePos);
}
private void OnDrawGizmos()
{
if (!Application.isPlaying) return;
Gizmos.color = Color.cyan;
Gizmos.DrawSphere(mousePosGrid, 0.12f);
Gizmos.color = Color.red;
Gizmos.DrawSphere(mousePos, 0.12f);
Handles.color = Color.yellow;
Handles.Label(mousePos, mousePos.ToString());
}```
looks like the float is being floored
I'm using WorldToCell is that what it does?
it might
Seems it might be , any ideas how to get it close enough?
not sure if I should ceil or round
round
ceil would put it in the top left corner
you can try to round the position before feeding it to WorldToCell
yeah I just ended up using mousePosGrid = Vector3Int.RoundToInt(mousePos);
glad you got it fixed
thanks for the help 🙂
I recommend you change from free aspect to a fixed aspect ration in unity when working with any UI. Problems like this tend to rise when you dont
youre welcom
Red x means it has negative width or height
none of the ebook links work in the pinned message for me - do they need updated?
They work for me?
Hm - have tried two different browsers as well.
Odd.
Question, though - is it possible to take a screenshot of a canvas consistently even when the size of the screen may change? The ScreenshotCapture class doesn't seem to work for it
@quartz folio here is the singleton in question. It manages data that must persist between scenes
You should link to large codeblocks in future; but yes, that looks fine, it destroys itself if there's another one already
My apologies, i'll keep that in mind for the future
I'm having trouble figuring out how to do accomplish this. Any ideas welcome.
- Have multiple small islands, around 10x10 tiles max
- Each island has tiles where buildings can be placed and some tiles where they cannot be placed
- Each island is a separate game object. I have a variety of them and will spawn them randomly on the map.
Everything is grid based, 16x16 tiles/sprites. Once I figure out how to properly store the data for each island I can then move onto working on placing the buildings on the buildable grid locations.
I think you don’t need gameobject per island, just load the layout then put it in tilemap or whatever you like
Why do I see a warning in my compute shader when defining a field with name point?
struct WaterSourceData
{
int3 point; //here
float amount;
};
Declaration does not declare anything
'point' specifier is ignored when there are no declarators
Not even that, applying these rules will expose various methods and properties that would exist in the type, now that it is restricted. You are very limited to what a Genetic can do if you do not apply any restrictions on them.
For example, restrict the generic to implement a certain interface, and you will have access to the implemented methods and properties from that interface.
Because point is a reserved name in HLSL. Specifically used in geometry shaders.
what libraries are good for game building withc++
How is this a unity related question ?
I use entt entity system
Unreal engine. 😬
:gasp: he who should not be named
SFML, but SDL is a no brainer pick too, but it's C sadly
sfml has a official c# binding at least, unlike sdl
oh forgot this is unity server 😅
why you want to do that?
ban comments? why on earth would you want to do that?
This is a load of shit
There are cases where comments are not needed and cases where they are very helpful. You can't really say "comments are not needed(entirely)"
Besides, if you have time to worry about that, you should spend it on development
Then you haven't had to deal with complex systems and big projects. From my experience I would pay money for there to be comments sometimes.
Comments shouldn't describe the code literally, but what the idea was behind a particular implementation, or what sources were referenced, or what to watch out for when maintaining it
again dude, code comments has nothing todo with clean code
Anyways, that should make it clear that no one hear knows how to disable them, since we never had a need in it.😬
Did you ever work in a team or a codebase that someone else wrote?
Many? mention the first 5 at least?
Well, great then. If you don't need comments just don't write them.
We don't need to go into bragging
If you want an answer go ask the C# Discord
Where they will probably also laugh
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
It's not a magical fairy, you don't need to believe in it. It's basic core practice.
@hot quest Once again you were pointed where to take it already.
anytime I think of commentless code I think back at my math professors writing computer algs without clarifying any variables and just expecting me to understand what everything is
just math professors and pseudo code in general
For the last time. Stop posting off-topic.
Move on, we don't need or want this discussion
!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.
there's something weird happening
I implemented the navmesh movement ai from unity in ecs
it works perfectly fine on the editor
when i make an android build or a windows build for that matter, it travels in a straight and gets blocked by obstacles
im guessing it fails to load the navmesh baked data on builds
is there anything specific that has be done for prebaked navmeshes to work on builds?
By sitting down with your team and discussing the use of comments in your project. Not everything can be handled with just well written code, comments exist to explain the harder to understand features.
also banning comments would be a massive mistake
Don't want to go off-topic again, but even simple comments very often can indicate what a block of code does, without needing to spend time figuring it out yourself
the code only says what is going on, it does not say why
you can write a simple program (leetcode medium level) to process your code......btw the discussion was end
Just wanted to vent my opinion since I severely disagreed with the take, but I was too late 🙂
//Prints Hello
Console.WriteLine("Hello");
Banned

in other topics AI have gotten better at commenting code
Does using Vector2.zero increase GC at all? Am I better off having:
Vector2 zero = new(0, 0);
void Update() {
if (randomVector != zero) foo();
}
OR
void Update() {
if (randomVector != Vector2.zero) foo();
}
I doubt it matters but Vector.zero looks cooler
xD
no gc pressure at all structs allocated on stack
Is there any overhead in the Vector2.zero call? If so, having a predefined private variable will eliminate this overhead.
no need to create your own var though
Just use Vector2.zero
Vector2.zero uses default(Vector2)
I've read that structs do generate some amount of garbo or something in the passed, but even if it doesn't I'm not changing up my unmanaged structs ;p (c# specifically)
probably fetching a static variable in somewhere may require little time, but not the reason that using extra 8 bytes to store it (one instance =8 bytes, many instance=many 8 bytes)
value types as far as i know like structs are stored on stack
GC only deals with heap
JacksonDunstan.com covers game programming
He's got a bunch of interesting stuff for microperformances
Love your work
events actually do generate a lot of garbo
Notice that neither “normal” non-generic struct creates any bytes in the “GC Alloc” column. The generic struct also has zero bytes in the “GC Alloc” column, but only when using the default constructor that takes no parameters. When using the non-default constructor that does take parameters, the generic struct suddenly starts allocating 32 bytes of garbage.
interesting
Ah, ok right now I remember this
Most people do this tbf
Also really old post 😄
I wonder if theres been any updates
Yeah, it is old but I came across this website because I was getting microstutters with subscribing
unity profiler is pretty nice for this
I think its got gc alloc somewhere in the chart
JacksonDunstan.com covers game programming
Which is what I've changed a lot of my subscription models to ^
😮
ty
Im also using unity events
I can see what this person is doing
public void Dispatch(int enemyId, Vector3 location)
Removing object completely
And using value types
If you're recieving a huge amount of events in a short time then this should be good
Basically, I've a bunch of abilities and stuff that listen to statistical changes
and then I do a lot of caching
*changing stats would prompt all abilities subscribed to update accordingly so I could cache their formulations without doing it throughout the usage, but more importantly would be my enemies spawning and subscribing to game related events when dequeued from my pool.
Not really much choice i got tbf but thankfully gc isn't a issue for me rn
Yeah, if it aint a problem, dont fix it lol
just took a look on new publisher-subscriber model
just having a hard-coded way to call manager first then probably call all the instances under manager
public static list<ABC> ABCs;
public static void SomeoneCallsOurs(args){
foreach(ABC a in ABCs){a.Listen(args)}
}
ABC(){
ABCs.Add(this);
}
public void Listen(args){}
```i do this if no "manager" is needed
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playermovement : MonoBehaviour
{
// Adjust the speed to your liking
public float movementSpeed = 5f;
public float jumpForce = 5f;
// Reference to the Rigidbody component
private Rigidbody rb;
private bool isGrounded;
void Start()
{
// Get the Rigidbody component once at the start
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true; // Freeze rotation to prevent unwanted physics interactions
isGrounded = true; // Assume the player is initially grounded
}
// Update is called once per frame
void Update()
{
// Move up
if (Input.GetKey("w"))
{
rb.velocity = new Vector3(0, 0, movementSpeed);
}
else if (Input.GetKey("s"))
{
rb.velocity = new Vector3(0, 0, -movementSpeed);
}
else if (Input.GetKey("d"))
{
rb.velocity = new Vector3(movementSpeed, 0, 0);
}
else if (Input.GetKey("a"))
{
rb.velocity = new Vector3(-movementSpeed, 0, 0);
}
else
{
// If no movement keys are pressed, stop the movement
rb.velocity = new Vector3(0, rb.velocity.y, 0);
}
// Jump with space key if grounded
if (Input.GetKeyDown("space") && isGrounded)
{
rb.velocity = new Vector3(0, jumpForce, 0);
isGrounded = false; // Set to false when jumping
}
}
// OnCollisionEnter is called when this collider/rigidbody has begun touching another rigidbody/collider
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true; // Set to true when landing on the ground
}
}
}
do you know whats wrong?
objects supposed not to be able to jump until it hits the ground
ground has a collider
@indigo hound hey. I upgraded my ClassTypeReferences to the fork that you are using, and noticed the UI breaks if there are 10+ types included in the single search. At 10 types, it changes to a search bar that references a broken Unity component. I fixed this by going to ProjectSettings > Packages > TypeReferences > Minimum searchbar item count.
Change this from 10 to 9999
You shouldn't be ignoring the console window
Alright, thx for letting me know!
tx 👍
Hi is there a downside to exposing auto properties to the inspector with [field: SerializeField]? like for public Vector3 TargetPos { get; set; } ? I know the backing field has odd syntax but not sure it matters
Not really, unless you consider cluttering your inspector as a downside
cluttering inspector? Well obviously I will only expose where required
just quicker than exposing a private field and then adding a property
I ran into a problem with this recently. I originally had an interface that called for:
public LocalizedString Label { get; }
Each implementor had:
[field : SerializeField]
public LocalizedString Label { get; }
I then switched to an abstract class that implemented the interface, and had:
public abstract LocalizedString Label { get; }
And thus I switched the children to have:
[field : SerializeField]
public override LocalizedString Label { get; }
At this point, Label stopped showing up in the inspector.
because you need set also for it to show up, that is why
You need to explicitly target the backing field.
The only downside is when you need to work on the backing field then it gets a little messy
via attributes and such which you need to target directly
yeah true! had bad tutorial
oh no not true...
you need field: is property
*if property to say backing field
If you look at the serialized data, you'll see something like this
<Label>k__BackingField:
So i want to have a changing amount of rigidbodies in 2d box, i want when 2 rigidbodies with the same tag to report to a controller script that will then do something with these collisions. how would i do this? i would assume events but there will be can i add more and less events whenever i want?
That's right. I did have a private set previously.
Oh, that's exactly what the problem was.
yes that is a bit lame if using to serialize items for saving etc, but not sure issue for scripts in scene
I got rid of it when I switched to overriding an abstract property because I didn't include that in the abstract property.
I just decided to switch to an explicit field anyway (it was easy to migrate with [FormerlySerializedAs]
followed by forcing the serialization of every asset
so I would not mind an explicit field but I would need an IDE tool to make it quick for me! I need speed and non-auto properties take time and more clutter!
you spend a lot more time reading code than writing code
so I would optimize for that case
also if you're using attibutes from naughty attributes you need to split it up such that:
[AllowNesting]
[SerializeField, HideIf("MovementType", MovementType.None)]
private Curve curveData;
public Curve CurveData => curveData;```
the private set is kind of icky because it changes the meaning of your property
(within the class, at least; it's not public!)
what about Json.NET - does it handle auto properties in any good way or you can help it do it nicely?
I haven't tried serializing auto properties before
just hasn't come up
everything I'm serializing is a regular field, actually
I think it does but yeah everything I use auto properties for are usually nothing im saving
I'm serializing configuration data that's stored in dictionaries. I present that data to my code through properties
I was originally just going to serialize it that way too
but I don't want my saved data to break if I rename the properties
I'd have an ID to the data object if anything
dictionaries also meant I had to write a wacky converter that would handle dictionaries whose keys need a special converter
in that case, I decided to just turn my dictionaries into lists of tuples and serialize those
good thoughts, thanks!
I'm still a bit wet behind the ears when it comes to good serialization, though
I'm just getting into the phase where I need to support existing player data 😬
instead of just breaking everything whenever I want
I have done a lot of terrible serialization, now I need to do it better - so Json.NET will be investigated for non editor stuff
Json.NET is pretty darn nice
I have a system where scriptable objects get a GUID (literally just the asset GUID)
i can fetch them all from Resources and then look them up by GUID
and I have a converter that handles that for me
public class IdentifiableConverter : JsonConverter<Identifiable>
{
public override Identifiable ReadJson(JsonReader reader, Type objectType, Identifiable existingValue, bool hasExistingValue, JsonSerializer serializer)
{
if (reader.Value is not string result)
return null;
Guid guid = new(result);
if (IdentifiableRegistry.TryGet(objectType, guid, out Identifiable ident))
return ident;
return null;
}
public override void WriteJson(JsonWriter writer, Identifiable value, JsonSerializer serializer)
{
writer.WriteValue(value.Guid.ToHexString());
}
}
(this came up when I used Identifiable as a dictionary key)
yes I need to use GUIDs to id things. So do you have to convert to from string?
ok so comparing GUIDs is much faster than string comparison right so better to keep?
or searching by etc
For my enemyController i have the prefab instances of the enemy in the editor
since the prefab itself is not in the game
does that mean that it will not work
i instantiate the prefab, which does ofc put it in the game
and that does not work
but if i place the prefab in the scene and assign all the stuff from that to my enemycontroller it suddenly works
but i cant use that because then when the prefab i put in the scene is destroyed im referencing something that does not exist so it crashes
🦧
gameobject in scene can reference asset
Which "prefab itself is not in the game"?
What prefab do you instantiate "which ofc put it in the game"?
The question/issue is not obvious to me, would be great if you could elaborate a little more precisely
The prefab in question is the prefab of the enemy]
you know how people tend to have a prefab folder
the prefabs in there are not in the scene
Ok, but the EnemyController is already in the Scene?
Why don't you let your EnemyController itself handle Instantiating/Destroying the Enemies?
yes it is in the scene
So i want to have a changing amount of rigidbodies in 2d box, i want when 2 rigidbodies with the same tag to report to a controller script that will then do something with these collisions. how would i do this? i would assume events but there will be can i add more and less events whenever i want?
i have it on a cube just under the map
i do have it doing that stuff
sorry i cant explain well
What exactly is the issue?
when i drag a prefab from the folder and into the scene, and then assign the parts of that to my enemyController in the editor
My enemycontroller works and the enemy does what i like
So, basically, your EnemyController needs to fetch some Data from your instantiated Enemies?
But that is not working because eventually the enemy is killed and then i cant reference it
yes that is what i need
Easiest solution would be to make your EnemyController the thing that instantiates and destroy the Enemy.
That way, it could instantiate it and immediately fetch the required data, and it could destroy it and clear the reference.
i dont understand
Minimal example
Enemy EnemyPrefab;
Enemy EnemyInstance;
Data SomeData;
void CreateEnemy()
{
EnemyInstance = Instantiate(EnemyPrefab);
SomeData = EnemyInstance.Data;
}
void DestroyEnemy()
{
Destroy(EnemyInstance.gameObject);
EnemyInstance = null;
SomeData = null;
}
Can i show you my enemycontroller code because i think i am doing that already
besides the enemyinstance = null i dont know what dat does
wait i think i see
Well.. it's setting the Reference to EnemyInstance to be null, because the GameObject got destroyed, so it won't exist anymore. Just making that explicitly clear with the = null
if this works i will be veryu happy because i have been trying to get my enemy to work since sunday
Feel free to share the Code (using a proper website like pastebin), as long as it's readable 😀
i will ping you shortyly after i try implementing that
You could simply call a method on another object in your OnCollisionEnter2D, something like MyCollisionProcessor.ProcessCollision(collision), if I understand your question properly.
Or use events of course
well, i want one script per rigidbody/gameobject. and when it collides, itll talk to the master script and say that its had a collision
and then logic will run on the master script and other stuff will happne
So basically, what I said 😄
Put a Script on your Rigidbodies that uses any of the OnCollision... methods you want and inside of that make a call to your "Master".
But you should probably delay the processing of the Collision inside your Master, so it doesn't process the same collision from both sides, as in, A and B collide and both have Rigidbodies and the Script, you don't want the "Master" to be called twice for the same collision
okay idk how to do it im showing you the code
!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.
i think most of the code is probably not stuff you need to read
for helping with this
Instantiate(enemy, new Vector3(0, 1, 25), Quaternion.identity);
You instantiate the Prefab but you don't store a reference to it? And do further work on the enemy which at that point is probably the Prefab?
if (enemy.GetComponent<CollisionDetection4Enemy>().collided)
This gets the component of the prefab, not of some instance, on the thing you pass into Instantiate, not the thing that actually was instantiated
i knew i was missing something vital and its been hard to figure it out
When you call Instantiate(somePrefab), you usually want to get a Reference to the instantiated thing
myThing = Instantiate(somePrefab).
Also, your EnemyController seemingly tries to handle multiple enemies, i'd recommend to have one EnemyController for one Enemy that's being controlled
okay and then do i do everything off the reference
Yo! I learned the concept of design patterns and I don't really know which to choose for my project. I want to make a souls-like, at first I thought that using singletons and managers could be a good idea but I read that this could cause problem later on in development when you want to change the parameter of a function for example. Observer patterns seems like something useful in my case, but I would like opinions from experienced people on the subject if possible. I know that there isn't one perfect pattern, but I'd like to have some guidance to know what to learn. Thanks!
This may sound easier/harder then it is, depending on your experience and use case, but you should try to make the Enemies "standalone", as in not have them require anything that's not included within themselves.
Exception being the Player, but that one could be referenced by a Singleton or a Service
the two enemies is for a thing where it doubles itself every time it gets killed but i can separate from it if i must
Hey!
There is no "this pattern fits it all", software is mostly a combination of many different patterns and some ugly hacks in-between.
It's not like "I want to create a souls-like, what pattern do I need" but more towards "I need to build feature XY, which patterns could be used for that"
Observer Pattern for example is something that you'll likely find in every software in some style, it does nothing in itself but only helps with decoupling
Ok thanks! So I should learn about famous design patterns and then try to figure out which one I should use for which problem?
What is te benefeit of having the enemies standalone
So, honestly, it's good if you learn the patterns and know how/why/when they do work, but you shouldn't worry about them too much, it's more important to actually get stuff done and you could always try to introduce/refactor towards patterns at a later stage.
I did both approaches, started with some patterns from the very beginning, and not doing so, and the first option comes with some technical debt that will slow down your development
Basically, testability, it's great if you can just drag and drop a prefab in your scene and it works without any additional setup.
Note that I'm not an educated professional and I'm just giving my opinions because nobody else does, burn me for any dumb things I might be saying 😄
I first learned about patterns because I didn't wanted to use GameObject.Find/FindGameObjectsWithTag/putting it manually In the inspector. But if you tell me not to worry about patterns how should I get my gameObjects without using these (if it is a good idea to not use this). In my head using these prevent my project from having scalability and modularity
Embrace the Inspector, it's great! Why do you not want to use it for GameObject references?
It's the exact opposite, Inspector does give you modularity by design, because you can change content without having to modify the code.
+1 for not using any GameObject.Find calls unless there is no other solution
can you show how i would reference the instantiated prefab in my code
Because I think that manually dragging my gameObject in the inspector will prevent me from having disconnected scripts. But I'm probably wrong
I want to be able to modify, remove scripts without breaking all my game
But I don't know if it is possible, if it is something to look for
Don't overthink, go in and test it!
I did, multiple times, scroll up 🙂
So, I should do it with the inspector ?
i know but i dont get it 🦧
Hey ! I would like to know if someone know a good Block/Parry system tutorial for a 2D Metroidvania game somewhere ?
Not for everything, but in most situations it's perfectly fine.
Could you give me an example usecase where you think it might not work?
And if I want to acces variables from another script I should also use inspector ?
My main question is for script in reality
How should I access other script without breaking everything if I remove one script
If you remove one script and it breaks everything, the script is doing too much stuff.
Keep your Scripts small and simple, have them do one thing
(Sorry if it's hard to understand me, it's not my main language)
You'd want to be forced to redo stuff in the Editor rather than hope nothing blows up
But you could attempt Finding and whatnot if you'd rather take the risk.
Thing is, you need to give us an example situation, there's not "one architecture" that works for every script you write, this currently seems to be complete on the theory side and not related to existing code, and how you'd theoretically do stuff is very subjective.
Let's say I have a script PlayerStats with all it's stats. How should I get the health of my Player from the UI ?
Why would you want to get the Health from the UI in the first place?
You want it the other way around, your PlayerStats should have some Events for SomeStatsChanged and the UI would pick it up. Your PlayerStats don't care if there is a UI or not
is playerstats temporary stats or hard stats?
Yes sorry, bad english
eg does playerstats have MaxHP or CurrentHP?
i just ask because it changes if you’re going to have multiple references
Ok so in this case Events is the way to go so there isn't any connection between the two scripts ?
either way, I would make a monobehaviour on a UI element. UI element has a reference to your player stats, where it can read
Only a one-directional connection from the UI to the Stats
I expect your UI script to be able to go get access via singleton
It's just an example I absolutely don't know how it would work x)
Singleton, or some MiddleMan Service that handles the Communication between those things, that way none of the two would break if you remove the other one because the MiddleMan simply wouldn't pass the call
lots of things in your game need direct access to your player, and to stats etc. There should be a single point of contact so everyone knows where to get that info. A singleton will help do that
I think you have answered my questions! I shouldn't focus too much on design patterns for now, it's when I encounter the problem that I should look for design right? And the inspector is something useful compared to what I was thinking?
it’s both
you should use both C# programming AND Unity’s inspector to make your life easier
Ok, thanks for the help!
anyway, a monobehaviour on your UI element can access your text component on the UI (eg a TextMeshPro GUI component). Then edit its text field
Single point of contact sounds good, but I'd argue that a Singleton is not a single point of contact
are you saying a singleton is not single, or not a point of contact?
you can easily make a singleton that just holds serialized references to specific gameobjects. And that’s all it does
I used stupid words, sorry.
Of course a Singleton is single and there will always be a single Singleton that's being spoken to, but that's kinda one-directional again.
I'd prefer having some Service in the middle of the objects that want to communicate with each other
that’s perfect
you can also use a singleton mediator, if you want it to be not one-directional. But just holding references to some objects is super simple one-way connection
the player has no business knowing about what is on the UI. A mediator is totally inappropriate here
It's the difference between getting a NRE or have nothing happening when the Singleton doesn't exist
I'd rather have nothing happening and then be like "oh, nothing happens, why? Aaah, I don't have a Player in the Scene"
you know a singleton’s GetInstance method is supposed to instance it if it doesn’t exist when asking for it
and if your singleton just holds references, then it can check that each reference isn’t null
Depends on the implementation.
Which comes with it's own set of problems
Otherwise, you can get issue with performance. Having random lag spike because you did not initialize the singleton at the correct moment.
guys, just use a stock singleton class implementation. which addresses issues
Let's say I have two scripts on a gameObject and in the first script I want to access a variable from the other script. GetComponent<Script2>() is the way to go ?
yes, IF you know the second script is unique
Unique in the gameObject or in all the project ?
Making frequent changes to a single script increases the chance of error and because the Singleton pattern often becomes a major dependency, changes to it will likely cause headaches in the future - especially if working with others.
if you have 2 collider2D, GetComponent<Collider2D>() won’t guarantee you get the collider you were looking for
And in this case how should I process ?
SRP and singleton are not mutually exclusive.
Option1: Serialize field with a ref to the specific collider you were looking for.
Option 2: GetComponents gives you an array of ALL components of that type on the gameobject
i use both. it depends on the case
static PlayerEvents
{
// Being listened to from UI
static event Action<float> OnHealthChanged;
static void NotifyHealthChanged(float value)
{
// Called by Player when health changed
OnHealthChanged(value);
}
}
I like this one better then a Player Singleton, nothing breaks if you don't have a Player, and nothing breaks if you don't have a UI
They are often coupled together to avoid having to properly reference stuff - giant bloated scripts or many different managers.
Okay, thanks! Didn't know about that
static classes with changing variables are bad juju
What variable is changing there, besides the event? 😂
That hate for static has to stop, it has it's place, I'd argue that an Instance object with changing static variables is worse
your teeth will rot, your hair will fall out, your balls will shrivel. you’ve been warned
They are, does not mean they need to be. The fact is, that whatever pattern you use you will still have this dependency at some point. And whatever pattern you use to make the dependency weaker (interface, observer, etc.) can be use with a singleton.
static classes are wonderful when you change any variables extremely rarely
or only in its constructor
singletons are normally better in that 1) you store info on the stack, 2) info gets wiped when singleton dies. Those are the two major advantages
You can use interfaces
You can serialized data
The other thing is, you can use this kind of thing for bi-directional communication that still doesn't break if one of the sides don't exist, for example to put a RequestFullHeal or RequestPickupItem in there which the Player would listen to. (The "Events" name ofc wouldn't be appropriate anymore in that case, just call it Service or whatever)
No Player? No Listener. No Errors.
he doesn’t need bidirectional communication
UI reads player health
UI reacts to player health
We should assume that he will need bi-directional communication at some point in a Souls-Like, shouldn't we
For a GAME
The HUD was an example that he gave for some context related to his question about Patterns, Modularity, Scalability
this was a hud lmao
I've started a war
mediator pattern is more advanced, and is something you can do, and is way beyond the scope of what he was looking for
You can learn a lot within this war, Singleton discussions will live on forever
Too much reading x)
download a singleton class implementation
Is it ok to use [HideInInspector] to hide a public variable ?
way beyond the scope...
Souls-like...
😄
Hey everyone,
In this tutorial we cover the controversial SINGLETON! Many people will hate me for teaching this but I think it is a useful tool to have, or at least know about when programming. Hope you learned something and thanks for watching!
Example video of singleton that exists in scene (Canvas Manager):
https://www.youtube.com/watch?v=v...
I'd rather opt to not use the Singleton pattern unless there ought to only be single instances of such a script. Ease of access sounds very nice and all but I find myself able to avoid such a design by placing a bit more effort in scene designing. Might be okay for something small or something quick though.
Yeah, putting some events in a static class is definitely more out of scope then having a Singleton that creates itself on demand and fetches the proper data it needs.
I do like Singletons and they have their place, but IMO not within a Souls-Like Player class
Usually no. that means it is storing a variable, but inspector isn’t showing you what is being saved
I learned about singletons yesterday and it looked really cool. The only downfall that I saw is it can cause problem in the future if you change for example the parameters of a function. You will need to change in every script the parameters when you call the function and this is bad
If I use a public variable I just let it show in the inspector then?
NonSerializedField makes a field not serialized, which also means it won’t show in inspector
i rarely use purely public variables
purely?
I still prefer to use singleton.
Almost never, if I do then it's for Editor Tooling, for public data inside Code that actually ships with the Game, i prefer Properties (or method based access) 😄💯
I normally do:
This saves a myValue, makes any class able to see it, but only able to be set privately (or by inspector)
[field: SerializeField] public int myValue {get; private set;}
Not having an AudioManager or IOManager seem to be a pain.
I now about public private, protected (don't know what it is). Is there other things ?
And static
This myValue can be read by any class, and only written privately. It is a property (not a field) so it does not get serialized.
public int myValue {get; private set;}
And readonly
Hey.. at least you've isolated each behavior to unique managers 😅
protected means the variable is allowed to be used by derived classes. If Parent has protected int myValue, then: Parent can use it, Child : Parent can also use it, but other classes cannot
This is cool, should I do some research on this so I can learn it? Is it something useful?
that is how I do the majority of my variables
This is why I say SRP can still be applied. Which was your major agurment agaisnt singleton.
Ok thanks
If you've put in the effort, it should be fine 👍
The vast majority of my variables are:
[SerializedField] private int myValue; // totally private and IS serialized
public int myValue {get; private set;} // not serialized, and other classes can read the value
[field: SerializeField] public int myValue {get; private set;} // IS serialized, other classes can read, and THIS class can modify```
these 4 are my bread and butter
Then I will look at that. Your example is litteraly what I want for my _movementInput variable
you might also want to know how to make custom properties
Here if you don't put SerializeField it will not show in the inspector even tho it's public ?
Will look at that thanks
Yes, Properties in Unity are not Serialized by default
public int MyValue {get { return _myValue;} // Shows backing field
set {
if (_myValue == value) return; // Do nothing if already the same
_myValue = value;
CallThisWheneverMyValueChanges();}
}```
Ok. Thanks for all the answers, really helpful and kind of you!
this is is how you make a property, which basically ties a function to the variable
so you can do stuff when changing the value, for example
btw, showing in inspector, and serializing the field are two different things.
Serialize = saves value. Show in inspector = can see in inspector.
By default, inspector shows values if and only if it is serialized. But this stops if you use custom editor, or use [HideInInspector]
This one would require you to use the Property instead of the Field internally as well tho, or you'd need to call BlablaChanged by yourself everytime you use the Field, but definitely much better then a public Field
changed it to public get and set
I will look at all of that then. I know nothing about these concepts!
fields and properties are core to programming in C#
to OOP in general tbh
just know that even if it works to just make all your variables public, don't. There are a lot of terrible side effects that will make your life difficult later
Ok 👍
This is kinda unrelated to the current conversation, but you might as well check out Reference Types vs Value Types and class vs struct
👽
one thing at a time
what is all of this
Yes, but knowing it's existence is good for me
focus on just serialization and access modifiers (public/private...) for now
learn that, then continue
isnt this how it should be done? whats even the alternative for this?
Likely he's doing so for single instances and observer pattern (subscription and whatnot)
well, yeah, you use singletons when there's a single instance (:
Still seems excessive though but if he's willing to manage it then 🤷♂️
it'd hardly be a singleton pattern if you had two things
But who manages the managers?
Hey there, trying to make a simple steering behaviour (seek) in 2D and acountered this problem how can I change "desired" to be vector2?
ooh, interesting -- what are you doing to load these?
I see you're using addressables
The ManagerManager Singleton!! 😂
so thers 2 ways to handle this? singletons or subscriptions? how do you subscribe to something thats located in an entirely different script though
these are two unrelated concepts
oh, can you say the alternative to having 30 singletons for everything like the persons screenshot showed?
My singletons, for reference
I have a good number of singletons that exist in my game scenes, as well as a few that live forever in DontDestroyOnLoad
including the almighty GameController
How can I make UI Toolkit Scrollview align its children from the center in a horizontal mode?
i'm writing another one right now!
Do you guys work in the video game industry or are you just passionate ?
hello ObjectiveManager!
they are all good singletons. Except maybe the singleton for my single inputaction asset
why are singletons considered bad then if theres no other alternative
I think they're prone to misuse
they aren't bad when you know how to use them
A lot of design patterns exist to reduce coupling between different parts of your game
You use protected and private members to limit exposure between classes
yeah. like you see when I use singletons a lot, I suffer from having my references being super easy to maintain.
You use events in the observer pattern to make it easier to swap things around
and to reduce the amount of hard-coded logic
it really sucks to have my life being made easier
Singletons let you produce Spooky Action At A Distance
everyone can see the singleton, always
There's two patterns -> singleton pattern or singleton pattern with service locator pattern ;)
typing intensifies
That's the big one.
The other problem is if your thing isn't actually a singleton.
For example! My game used to have a single "player" entity that was special
The player could have objectives, for example
if there is ever any doubt that something will need multiple instances, you cannot make it a singleton. that's just asenine imo
But now many entities can have objectives. I need to redesign some stuff.
(there can also be zero players, too)
this is where the service locator pattern comes in which adds that extra abstraction to enable it
am i right that there are no alternatives for singletons? for example the AchievementManager. in some random scripts you are calling AchievementManager.Instance.UnlockAchievement(achievementname) right? is that proper use of singleton by the way? and also what even would be the non singleton way to do this?
The Universe 😛
for reference, I am making a single player game. I still don't have any singletons that would make me really forced to single player
don't need it. not necessary. not beneficial
you have to ask yourself if there's always going to be exactly one instance of your thing
in this case, that sounds okay -- but what about a multiplayer game..?
The non singleton way would probably be events, AchievementManager listens to stuff it cares about and decides on it's own when to unlock something, but idk
also like 99% of my gameobjects get instantiated from prefabs during runtime. I literally can't serialize references
If each player's game has its own achievement manager, and you aren't seeing other player's achievement managers, then that's fine
At launch (Async) or with [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
The observer pattern generally has no idea who it's subscribers are which makes accessing with a static reference easier and because it's a single instance, it's fine. But managers are often boiler plates for simply decoupling direct access to references (you may be referring to a player manager that would then reference players for others - they were added as intermediaries for the sake of simply being there and most often can be excluded)
What are you using the most?
Okay, so these live forever
makes sense
what do you mean?
They do, otherwise they would not be a manager. At least, in my terminology.
so this is the preferred method to handle achievements in singleplayer?
I use lots of singletons
What are the pattern that you use the most (if this question makes sense)
Fair, yeah. I have a bunch of components that only exist inside of a live game scene. I might just make them live forever (and correctly handle scene changes)
spending an hour on discord instead of making my game...
the main patterns I use are probably singleton, strategy pattern, observer pattern. There's a lot of other patterns that are really basic, but I don't even think about them because they are just part of normal business
😭
Completely unrelated to this conversation, and idk if that's even considered to be a pattern, but I think i haven't used anything as often as StateMachines, they work for the whole state of the Program, for UI, for Gameplay, for Actors, blabla
xDDD
i fell in love with state machines a few months ago
State machine, I will look at that thanks
I don't use any explicit state machines. Just enums that do a similar job
it's basically a finite state machine.... but not fancy
private bool exploded;
public void Explode() {
exploded = true;
}
in a sense, this is a state machine..
states are hard because it requires to actually debug
is it just fine, or is it the best way? i want to learn the best practices to avoid spaghetti code
the best way to avoid spaghetti code is to write it!
then to find out why it's bad for your game
and then to work out how to avoid that particular mistake
For me, the hardest thing about States is when they need some shared data between those, there are of course a hundred ugly ways to accomplish this, but idk for a clean way besides some type of DI
look at me, telling people "make your game" while I'm sitting here, not making my game
back to work!
AchievementManager is the one responsible to unlock the achievement. In the case you have player, you would have another concept in between.
Player -> AchievementHandler -> AchievementManager -> PlatformManager by example
Or another layer for networking where you'd have NetworkManager with a set of Players, but clients would also already cache a reference to themselves
This is what I have at the moment for the Manager. If I had to make it per player, I would change the progression handling part.
public class AchievementManager : Manager<AchievementManager>
{
public List<AchievementDefinition> m_AchievementDefinitions;
public EventManager EventManager { get; private set; } = new EventManager();
private Dictionary<AchievementDefinition, float> m_Progress = new Dictionary<AchievementDefinition, float>();
public void Awake()
{
foreach (AchievementDefinition achievementDefinition in m_AchievementDefinitions)
{
achievementDefinition.SubscribeEvents(EventManager);
}
}
public void OnDestroy()
{
foreach (AchievementDefinition achievementDefinition in m_AchievementDefinitions)
{
achievementDefinition.UnsubscribeEvents(EventManager);
}
}
public void UpdateProgress(AchievementDefinition definition, float progress)
{
if (!m_Progress.ContainsKey(definition))
m_Progress.Add(definition, 0.0f);
if (m_Progress[definition] >= progress)
return;
m_Progress[definition] = progress;
PlatformManager.Instance.UpdateAchievement(definition, progress);
}
}
Question on assemblies, since I learned about the issues where every asmdef needs to reference EVERY single dependency. How do I make an asmdef that automatically figures out: if I depend on X depends on Y, then I depend on both X and Y?
yes, thanks
You mean as an editor tool or something? You don't have to reference everything your references reference, only if you actually use the types in that assembly. If Assembly A has a method that returns a type from Assembly B, then of course you need to reference Assembly B too. But if the method just uses the type internally, then you don't need a reference to Assembly B.
ok, I think I'm getting the hang of it a little
but this still seems like it could become really tedious
ok so.... lets say that I have 10 classes that all need special internal access to each other. A couple of these 10 classes needs access to my main assembly, and my main assembly needs access to that one main class. Is there any way to split their assemblies?
maybe this is just the wrong way to use assemblies
what is the point of AchievementHandler and PlatformManager here? why not just call AchievementHandler.Instance.UnlockAchievement(achievementname) straight from Player?
also arent assemblies completely useless if you got singletons? because all your singletons are being called from any of your scripts. AchievementManager singleton would need to be called from everything that can give you an achievement (and that could be anything)
PlatformManager is the interface for diverse platform. PC, PS, Xbox.
AchievementHandler would be responsible for the achievement associated with a given character. By example, keep track of the current achievement that has been unlocked.
AchievementManager is responsible for all things that relate to achievement in general. By example, managing the instantiation of the diverse handler.
so for a singleplayer game, there is no need for AchievementHandler and AchievementManager to be separate things? also what about the assemblies?
It depends, the idea is to keep everything cohesive. By example, in our game we only have achievement for the "main player", thus we do not need to make the distinction between players. Hence, only an achievement manager is necessery.
Ok that makes sense. but how do you handle different assemblies? because so many things need to call AchievementManager for example and so many things calling all your other singletons too. or do you just keep all the scripts in one assembly and arent bothered by the load times?
What do you mean by assembly ? If you mean the code assembly, then I do not divide in different assembly because we do not have the need for the moment. That being said, if I were to do that, everything that has a reference on something that is not directly related to an achievement would be out of the Achievement assembly.
In other words, the implementation of the achievement would be in a different assembly that the code handling the logic of the achievement.
In the general assembly of the game.
[CreateAssetMenu(menuName = "Definition/Achievement/DefeatEnemiesUsedAchievementDefinition")]
public class DefeatEnemiesUsedAchievementDefinition : AchievementDefinition
{
public int m_Amount;
public override void SubscribeEvents(EventManager eventManager)
{
eventManager.Subscribe<EnemyDefeatedEvent>(OnEnemyDefeated);
}
public override void UnsubscribeEvents(EventManager eventManager)
{
eventManager.Unsubscribe<EnemyDefeatedEvent>(OnEnemyDefeated);
}
private void OnEnemyDefeated(EnemyDefeatedEvent e)
{
AchievementManager.Instance.UpdateProgress(this, (float)e.m_AmountDefeated / (float)m_Amount) ;
}
}
In the Achievement Assembly
public abstract class AchievementDefinition : ScriptableObject
{
[SerializeField]
private string steam;
[SerializeField]
private string xbox;
[SerializeField]
private string playStation = "";
public string ID
{
get
{
#if UNITY_EDITOR
return "";
#elif UNITY_XBOXONE || UNITY_GAMECORE_XBOXONE || UNITY_GAMECORE_XBOXSERIES
return xbox;
#elif UNITY_PS4 || UNITY_PS5
return playStation;
#elif UNITY_STEAM
return steam;
#else
return "";
#endif
}
}
public abstract void SubscribeEvents(EventManager eventManager);
public abstract void UnsubscribeEvents(EventManager eventManager);
}
ok, thanks!
Hello, is it ok to ?.Invoke() an unityevent in awake? im wondering because some gameobjects might not be done with their awake? I also just wanna invoke it only one time and i keep enabling and disabling the script during runtime
Start will also run only once on a objects lifecycle, so if you want to be sure a dependency in Awake is ready, you can call it in Start instead, often Awake is best used for data you know you have like GetComponent on a object you know has the component, though technically theres nothing wrong with trying to do a ?.Invoke theres just of course a chance the invoke never happens, because the order of Awake is up to Unity and AFAIK, is mostly random/inconsistent - and if your curios: https://docs.unity3d.com/Manual/ExecutionOrder.html
how can I rotate enemy acording to his movement? this is my enemy movement script
Ahh thank you, I misread and thought start gets called on every enable
sorry i wasn't in front of PC.
it's "more correct" but still has some major flaws.
for example
enemyInstance = Instantiate(enemyPrefab, enemyPosition, PlayerRot);
enemyInstance = Instantiate(enemyPrefab, enemyPosition, PlayerRot);
{
health = 3;
health = 3;
}
this won't work as you expect.
- you are overriding the Enemy Instance, if you want to handle multiple Enemies from that single class then you need to put them inside a Collection (List<T> for example) and access them by a ID or something.
- the
{ ... }block is not setting the Health for the Enemies, it's setting the variable inside that class to 3, twice in a row. the{}are obsolete there, your IDE should tell you that they are not needed because it doesn't know what you actually want to do.
you wantHealthto live on the Enemy itself, not on the EnemyController, because different Enemies will different Health Values.
another issue are this parts
Vector3 enemyPosition = enemyInstance.transform.position; // In your Update
enemyInstance = Instantiate(enemyPrefab, enemyPosition, PlayerRot); // In your Update as well
if (Physics.Raycast(enemyPosition, directionToPlayer, out hit, Mathf.Infinity)) // In your CanSeePlayer
you have a variable in that class called enemyPosition, you don't want to declare another local one inside of the Update, you want to assign it to the variable that lives in that class, which again doesn't work as you want it to do if you're managing multiple Enemies inside of it.
The EnemyPosition should (obviously) go on the Enemy itself, not in the Controller
I want to learn C# so I bought a C# book. However, it was published around 2002. Is this book still relevant to learn from?
the basics are probably still relevant, yes, but there may be some deprecated/obsolete stuff in it and nothing about newer features (which are quite a lot since then, i assume).
i'd read it and then continue education via YouTube (or some online courses) 🙂
mostly
how do i put it on the enemy itself when its an instantiation
your enemyPosition is only a copy of enemy.transform.position .. you don't need that variable at all.
in general, i think my suggestions won't fix your Script, you need to rethink what you are trying to do.
people in here might be well capable of helping you further if they knew your goal.
it's definitely not the best approach 😄
for example, why does the EnemyController check if the Enemy sees the Player, why doesn't the Enemy itself know about it?
Why doesn't the Enemy know about it's own Collider or Renderer?
why does it know about the Players Gun?
You can solve most of the problems if you just scrap the EnemyController and introduce a proper Enemy class which is, as i advised earlier, standalone
the collider script i have on the enemy already breaks the game when it is killed because then im referencing something that does not exist
i need to know how to have everything not break if something on an enemy is referenced before i go and add more things to it
why does the navmesh agent doesent send a error instead of not moving the NPC?
I try to change the target but the NPC starts standing and running in place if I try to change the navmesh target
not enough info
me to, because it doesent send me a error.
does someone know a lot about unity Facepunch and online with steam ?
dont ask to ask
mhmm, definitely not enough info, as navarone already said.
one possibility is that the Path is simply invalid, afaik you only get an Error if the Agent is not placed on a NavMesh.
btw we have #🤖┃ai-navigation here, not sure but i think that's the proper channel
there is agent and it is walking but if I want to change the route like following another empty gameobject, it stops moving completely.
I'm not even sure how to disable it because its not C#, its Unity specific what a navmesh Agent is and works.
I tried to disable the gameobject what the navmesh agent is targeting on but it doesent help.
I tried to reset the path and set a new one with:
[SerializeField] private Transform PlayerTargetPosition;
var_navMeshAgent.ResetPath();
var_navMeshAgent.destination = PlayerTargetPosition.position;
But IDK its not helping.
?! SetDestination is probably preferred? does that change anything if you use it?
no need to call ResetPath if you're setting a new one in the same frame i think
how can i detect if an ontriggerenter2d collider is on a certain layer?
Does this have to run only once or always inside of a update as long the NPC should move?
does collider.gameObject.layer return the string or an int?
it seems to return an int but is there a way to compare it to some LayerMask layerMask ?
you set the destination and the NavMeshAgent does it's thing, if you want another destination then you call the method again, no need to call it every frame
do I have to reset it if I change the destination to another?
The NPC is still running on place, wtf.
as written above
"no need to call ResetPath if you're setting a new one in the same frame i think"
do you have a proper value for Speed on the NavMeshAgent?
you can use hasPath and pathStatus to debug further
ok, I outcommented every resetPath with "//" and now it works, thanks.
https://www.google.com/search?client=firefox-b-d&q=unity+check+if+layer+is+in+layermask
idk if that's what you're looking for
Hi All,
Is there a good tutorial on what pattern to use to manage UI states, for example:
- Idle UI
- Building a building (dragging it)
- When you are placing a building you have a pop-up to configure it
- If during step 3 you press esc instead of enter - you go to step 3 where you are dragging the building around
is Screen.fullscreen always false in the editor?
to manage UI states ..
StateMachine? 😄
I've seem people talking about decorators, state machines something else
so have no clue where to start
i think so, most of the Screen... works in build only, but i may be wrong
alright ty
State Machine, definitely, i doubt that Decorator proves useful in your situation.
Don't stop at "people talking about Pattern XY", instead do some research and learn about that pattern, patterns are fun! 🙂
for your question, depending on the scale of your game, an Enum based StateMachine could already be enough
ty!
i can show more scripts if you're confused on what's going on
you always call ChangeHeightLevel, maybe you want to return out after the Debug.Log?
you are setting dynamicColliderHeightLevel on the collider but using another variable to add to the list
return so your ChangeHeightLevel doesn't run if if(colHeight.startingColliderHeightLevel + (int)entityHeight == 0)
but the collider will still be in the wrong level so it doesn't really fix the problem
I'm confused, i set dynamicColliderHeightLevel and then used it to add to the list, did i not? Unless this isn't what you meant?
no you did not
colHeight.dynamicColliderHeightLevel =
is not
[dynamicColliderHeightLevel]
imagine dynamicColliderHeightLevel is n, ChangeHeight level adds it to the nth list in the list of lists, which may be confusing i know
so i did set dynamicColliderHeightLevel and use it
you are the one that is confused, I can read code
HeightManager.heightManager.levels[currentColliderHeightLevel].Remove(col);
HeightManager.heightManager.levels[dynamicColliderHeightLevel].Add(col);
currentColliderHeightLevel = dynamicColliderHeightLevel;
what exactly is supposed to happen here, can you just give a mocked example with actual numbers? xD
do you eventually want to do this in a different order, Remove -> Change Variable -> Add?
the code looks good, can't spot issues with those 2 snippets
yes but you said i did something which i didnt,
what exactly do you mean by this
sorry, my bad you call the method on the changed instance
so currentColliderHeightLevel is the list it was in before the height levels changed, i remove it from that list, then set it to the dynamicColliderHeightLevel, which was changed by the CorrectColliders() function, adding it to the correct list(or so it's supposed to) and then currentColliderHeightLevel is set to dynamicColliderHeightLevel
the problem i'm having is that it randomly adds the colliders to the 0th list (yeah i'm calling it that) when it shouldn't
not sure if this matters but it also never added more than one list to the 0th list at a time
oops 🙂
Oh sorry again 😭
no worries, that was my fault
so you're saying you don't know why my problem is happening? the weirdest thing about is that the variable startingColliderHeightLevel is more than 0, and the variable entityHeight is never negative, so it should never be added to the 0th list, which is why I'm pulling my hair out because i can see absolutely nothing that could be causing this.
is startingColliderHeightLevel always >= 1?
i'm not sure tbh but i think (int)someFloat rounds down by default, may be very wrong with this and idk how to google this xD
This may also be important to add but i also have jumping and kind of a height System in my top down 2d game, as you can probably see, and this problem only happens when i'm on a platform and jumping at the same time, but you'd probably need the scripts for that stuff if you wanna see whether or no it's causing this
it's always more than 0, sometimes, yes the entityHeight plus the startingColliderHeightLevel is 0, but that is when the player is on the ground, where i want te level to be 0, this problem is only happening when the player is on a platform and already jumping, basically furthest from the ground, yet this stuff is happening.
is there a way to retreive the LookAt without applying it ?
Quaternion.LookRotation
ty
but i dont know well how Quaternions work, how can i set the Z rotation with a Quaternion ?
also yeah (int)float does round down but i want it to always round down anyways
Hi. I have set waypoints for enemies, and if the player is not nearby, they should move between these waypoints. In the editor, it works as intended without any issues, but on the phone, only the first type of enemy I created is moving correctly, while the others are attempting to go to point 0. Additionally, there are three types of enemies, and I created a prefab for the first ones and added the others. There is a problem with the others. I tried removing the prefab connection, but it's still the same. However, in the editor, it works correctly in both ways as it should. Can someone help me about it please
Yo! I have two scripts PlayerInput and PlayerLocomotion. I want to add rotation logic depending on the Input. Should I create a third script PlayerRotation or is it overkill ? I don't know where to draw the line of "one class = one thing"
i think those two scripts are too much in the first place
they should probably all be in the same script
or put the rotation in the playerlocomotion script, but definitely not 3
Ok thanks! How can I know when to stop applying one class = one thing ?
read up on Single Responsibility
if your script is very clear on what it does no reason to cram everything in 1 script
debugging / extending anything later will be painful
I'm not experienced enough to tell you this lmao
That's what I'm talking about. But In my case rotation is closely related to locomotion, but it isn't necesseraly the same concept. Following the srp I should create a third script but I don't know if it's overkill
is rotating the player ?
Yes
Up to you how you define the responsibility, these are just outlines for keep clean and clear code that is simplle to addon
just bumping this up here again, i haven't had a fix for it yet.
If you consider it part of "Locomotion" then its okay to do it, if you think there will be more than just rotating or what if you need it to rotate something else that doesn't move?. Things like that
I think I'm gonna create another script, and if someday in the future I see that the script isn't moving that much I will move it to the locomotion script. This is a good idea?
whatever keeps it more clear for you. There is no set rule, only some general guidelines
the objective is to keep it clean and clear for yourself or whoever works on it
Ok, thanks!
despite me editing the collider's values on the animation and the animation playing, they don't actually change in the game
they are grayed out for some reason
that's just me selecting them
Ohh I see
still looks weird
show the animator
how do you transition to this clip, nd are you sure the keyframes aren't skipped?
this is prob not code related though and prob goes in #🏃┃animation
hmm yeah the keyframes seem to be only on the first frames, so def check transitions arent skipping the keyframe
i then put it first and last frames and it still didn't work
I'm using a ruleTile, is there a way to have the ruleTile adjust if it finds any tile is found (aka not one part of the ruleTile rules? i can share code and picture of what's occurring if needed
I'm not sure Id ask in #🏃┃animation
why Random.Range is max Exclusive, i do not know
is that a question?
is it required to be? it can be, or it can be a statement
like do you want a fix?
more a curiosity thing.. is there like a Random.RangeInclusive?
floats
true
you can have a random.rabnge with floats yeah
or just put 1 more int above
and cast it to an int or round it
sounds good. thanks guys
yw
or make an array of ints and use .lenth , bam you have inclusive now
(don't do it its a joke)
but notice how with .Length it does become inclusive
interesting! hmm. something to keep in mind
in one my my projects I am using a the google sheets api. This uses google authentication api which uses Newtonsoft.Json. My project throws the provided error when build with webgl when ever a google sheets api call is made. Through research I have determined that this error is caused by AOT. following this guide: https://github.com/applejag/Newtonsoft.Json-for-Unity/wiki/Fix-AOT-using-link.xml I created a link.xml file and included it in my assets folder. here is the contents of my link file ```xml
<linker>
<assembly fullname="AssemblyCSharp">
<type fullname="usesJson.handleLogin" preserve="all"/>
<type fullname="usesJson.USER" preserve="all"/>
<type fullname="Google.Apis.Auth.OAuth2.JsonCredentialParameters" preserve="all">
<method signature="System.Void .ctor()"/>
</type>
<type fullname="Google.Apis.Auth.OAuth2" preserve="all"/>
<type fullname="ewtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewObject" preserve="all">
<method signature="System.Void .ctor()"/>
</type>
<type fullname="ewtonsoft.Json.Serialization.JsonSerializerInternalReader" preserve="all"/>
</assembly>
</linker>
Newtonsoft.Json (Json.NET) 10.0.3, 11.0.2, 12.0.3, & 13.0.1 for Unity IL2CPP builds, available via Unity Package Manager - applejag/Newtonsoft.Json-for-Unity
I asked at animation but asking here just in case too
I'm trying to change my collider's size and offset through my animator so that it changes when I change direction, but when on runtime it stays at default. Yes I did check that the animations are being properly played. Then to test I tried setting the size at (0,0) at the first frame and then at (1,1) after one frame, and instead of the size changing like that, it became the default size X and Y values +1
Yo! In general should I Use Unity or C# events? Right now I have a PlayerInput script and when I press a certain key I want to call an event that will do something in another script. What is the best here?
UnityEvents are for exposing events to the inspector. If you are not doing that, then don't use them
Perfect, thanks!
helllo
how come the enemies i instantiate after the first enemies death
do not do anything, unlike the one which is instantiated in the start function which works properly
i did not get what that guy wanted so i am hoping for an answer i get
you do know you can ask follow up questions, right? don't just crosspost to a different channel because you didn't understand the reason provided to you.
the answer is still the same though. you only operate on the most recently spawned enemy because you're only storing a reference to one enemy
there are beginner c# courses pinned in #💻┃code-beginner if you do not know how to create an array or a list.
praetor's second point about your spawner also managing the behavior is also a good point. why not have the enemy objects handle their own behavior and just make the spawner handle spawning them
i have been having issues with that since i cant assign anything thats not also a prefab to a prefab in the editor
pass any required references to the spawned instance from the spawner
https://unity.huh.how/references/prefabs-referencing-components
this is good knowledge
How would i edit a .data file
can you be more specific about what exactly you are trying to do?
convert it to human readable
why not just write it in a human readable format in the first place?
Because the file isnt from my game
i just want to edit the file
figured i might as well come to this server
as its made in unity
modding discussions are not permitted here. if you want to modify a game then go to that game's modding community for help.
the modding community doesnt exist as its an android game but alright
Hey there, in my game I use the following code to create an instance of PlayerMovementStrategy, but it gives me this warning. It says to use AddComponent, but when I try that, it gives me an error. What would be the best way to solve this to not get any errors or warnings?
Option 1: Gives Warning
public void CreatePlayerMovementStrategyInstance(PlayerPowerupState currentPlayerPowerupState)
{
currentPlayerMovementStrategy = Activator.CreateInstance(currentPlayerPowerupState.playerMovementType) as PlayerMovementStrategy;
}
Option 2: Gives Error
public void CreatePlayerMovementStrategyInstance(PlayerPowerupState currentPlayerPowerupState)
{
currentPlayerMovementStrategy = currentPlayerPowerupState.AddComponent<PlayerMovementStrategy>();
}
📃 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.
Probably a useless question, but is this statement still true ?
Should i use jagged arrays rather than multidimensional arrays ?
if that is true I laugh
Considering Unity uses a .NET version that released in 2012, most likely yes
That accessing a multi array is slower ?
I'm genuinely curious if that is true so i'm going to write a quick benchmark for it and find out
I have to stop my computer, could you please @ me with what you found ? 
Ty
when saying theres an error, you should also specify what the error is, what line its on, etc,
do what unity tells you, by using GameObject.AddComponent
https://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html
Not really sure what your PlayerPowerupState is but its not a GameObject
CreateInstance is for scriptable objects, is that what you want?
Show us the details pane - are these where the errors were triggered? Option one warns you that you shouldn't be creating mono behavior scripts with the new keyword - opt for Add Component instead. Option two suggests that you're calling an unsupported method on something.
Need type info
We'd need to see the implementation and test
Before going to sleep i found this
https://docs.unity3d.com/Manual/BestPracticeUnderstandingPerformanceInUnity8.html
@somber nacelle sorry for the @
I think I got it, I just had to remove the monobehaviour on the classes I used which removed the warnings and errors. I found out that a monobehaviour has to be attached to a gameObject which I didn't know, but now I do
Unity 5.3 is really old
yes, not the newest, but certainly newer than unity 5 was using
🤔 how did you get past Hello World without knowing that?
Lets wait the benchmark ig
I guess I never heard or learned that
Everyone starts somewhere ( #💻┃code-beginner might've been the more appropriate place to ask the question)
if playermovementstrategy is a Monobehaviour (it should not be), then you want to AddComponent it so other components can find it easily, when tied to the gameobject
Monobehaviours get attached to GameObjects because that is how Unity knows to get calling Awake, Start, OnEnable, Update, etc…
but that is unnecessary overhead for a POCO (plain old C class), that doesn’t need any of that behaviour
your PlayerMovementStrategy should typically have 0-2 fields in it, because the whole point is mostly to pass on the strategy. Ie the specific function/algorithm you want to use
it’s job isn’t to maintain/manage major aspects of a player’s state, if that makes sense
Yeah I actually never learned that it's supposed to be attached to a gameObject. The rest I somewhat knew, but thanks for the heads up anyways!
it’s ok. learning is just a part of the process
Benchmark Code: https://paste.mod.gg/uxdjbkfetrgu
Setup used: Unity 2023.2.3 targeting .net standard 2.1 with Performance Testing Extension for Unity Test Runner
So fully iterating through the 3d array is slower than fully iterating through a jagged array of the same size using for loops. It is a rather significant difference at about 4 times the median speed
Randomly accessing an index is so fast for either that the difference isn't even something worth worrying about.
That's really curious.
3D array more jagged than the jagged array it seems
it’s worth noting the random access is 100 accesses, and full array was 10^6 accesses in that code
it’s super weird that jagged is faster than 3D array
Yeah had to do 100 access for random access to even get any time on them. So really unless they plan to iterate their 1 million element arrays all in a single frame, there really isn't much point in worrying about the performance impact of either.
The fact that there is such a huge difference in the sequential access is rather curious though
arrays in general are fast as fuck
it’s their job
a job they are very good at
it’s weird since i expect a jagged array to access by 3 pointers, while a 3D array to be doable by one pointer + fast math
the regular one is fastest, the others are depends or may not be as fast
multidim arrays need to GetLength() while the regular array can access the length directly for bounds checking
Jagged array is just regular array under the hood, it should be faster than multidim
For prefab instances that were placed in the scene in the Editor by hand, should I be able to destroy these from script using Destroy(prefab)?
At runtime?
No
Actually just no, not ever. You need to destroy the instance, not the prefab. The prefab will be the object was that was copied.
Yes the "prefab instance"
So you drag it from the project folder, into the scene, it's an instance of that prefab. Then during runtime, I target it with script and try to destroy it so it's removed from the scene. It doesn't work
Can you show the code?
With the little info you're giving, I suspect you're probably accidentally destroying a compponent on the gameobject instead of the gameobject inself
It's an easy mistake to make
Ok but it SHOULD be possible, right?
i.e. Destroy(someComponent) instead of Destroy(someComponent.gameObject)
ok that's exactly what I'm doing, so there you go
Gday everyone, i have a script on an object that also has the same script attached, when these objects collide they are meant to spawn a singular object. but this is not the case though
it spawns two (because the script doesnt know the other script exists i believe?)
whats one of doing this, could i remove the script from the other object to combat this?
One possible solution is to add a flag like bool hasSpawnedObject. Whenever it collides and hasSpawnedObject is false, spawn the object, then if the object it collided with is the same type, set its hasSpawnedObject flag to true. Else, if hasSpawnedObject is true, then reset it
OnCollision(EventArgs e) {
if (hasSpawnedObject) {
// reset flag
hasSpawnedObject = false;
var collidedObject = // Get the collided object
collidedObject.hasSpawnedObject = false;
}
else {
// Spawn the object //
var collidedObject = // Get the collided object
collidedObject.hasSpawnedObject = true;
}
}
There may be a more efficient method though. This is just what came to mind
well on both scripts the Event happens at the exact same time, right?
I'm not sure
No. Computers can only process one line of code at a time on the same thread. What happens is that all the target objects get notified in arbitrary order.
then why on earth is it spawning two, is luckybread's answer correct?
Ideally, you want one script to manage the spawning in this situation. Create some kind of Spawner manager that would spawn and keep track of your object. This way it wouldn't spawn it twice if it knows that it's already spawned.
Probably. You never shared any code so we don't know wether you're doing anything to prevent it.
ill try luckybreads method than ill see what i can do about a spawner manager
in the mean time, what would that look like?
So i want to have a changing amount of rigidbodies in 2d box, i want when 2 rigidbodies with the same tag to report to a controller script that will then do something with these collisions. how would i do this? i would assume events but idk - I asked this question yesterday and nobody got back to me
essentially what youve told me to do
Something like
Collider.OnCollision -> Manager.Spawn(objectId)
You could use events or call a method on the Spawner from the collision. Up to you.
Aha
Luckybread's method worked
Thanks for the suggestion though, ill keep it in the backlog if i find more errors
If I needed a word that describes what Classes, Structs, Records, Enums, Interfaces, etc. were, what would it be? Types?
in C#, classes, structs, and records are all user-defined types
for Interfaces you can think of it some sort of a contract
much quicker if you just google these
No, they are keywords which are used to define different kinds of Types, they are not types in themselves
well do you have a word? Best I and c# discord can come up with is User-Defined Types.
that's 2.5 words.
Type definition keywords is about as small as I can get it
or even object definition keywords
in this statement
public class MyClass {
the type is MyClass not class
structs are objects
and interfaces can only be used in combination with an object and can be treated as such
as for Enums, because they rely on an underlying primitive type, which are also objects, they too can be thought of as objects
Basically an instance of anything is an object.
Greetings, maybe the correct place to ask. Newbie here, was wondering maybe someone can explain how unity and rpg maker C# differ?
Same language, but they feel so different to code
In one word, API. The C# used is identical except possibly for version, the API calls will be wildly different
Way more clear and huge of unknown again ^^
Based of this, can I guess that plugins that would make the coding similar is not likely?
Actually where would I look for unity plugins?
not at all but, would not be that hard to make
Really?
Could a newbie do it?
no
ohhh, yay and ohhh
you would need to know the API's of both systems really well
btw you can find Unity plugins both on Github and the Unity Asset Store
hey anyone know why when using fixed update the detection for space bar like barely works but removing it then it starts working fine? i thought it was supposed to be better to use fixedupdate for like physics things, or atleast thats what ive heard, sint jumping related to physics?
input detection itself is not related to physics
physics, yes. catching Input, no. So you need both, Catch Input in Update, consume it in FixedUpdate for physics
fixed update does not run parellel to your frames, while GetButtonDown is only true for one frame. if there are 2+ frames between a physics loop then its likely going to be set to true and back to false before FixedUpdate.
You can actually keep that jump code inside Update, because your ForceMode is impulse, which is a one off thing. It happening once in update vs fixedupdate will not have a noticeable difference.
As for the line above, where you AddForce(0, 0, forwardForce * Time.deltaTime), you should remove the Time.deltaTime and keep that inside FixedUpdate. The equations used by addforce already take deltaTime into account, so you shouldnt be using it here.
thanks im very new to this all, had no idea addforce already accounted for it, thanks so much!
Thanks for the help! Found Gamemaker as probably the closest example
how can I get a transform to rotate with a game object? the InteractionPoint follows the player in xyz axes but it doesn't turn with the player
Sounds like Body is the object that is rotating, not Player so you have a couple options. You could make InteractionPoint a child of the Body object or you could use something like a rotation constraint
I'll probably just go with making it a child of body since it's going to be following it around anyways, but whats a rotation constraint?
a component that does exactly what it sounds like it does
hello,
i got an array of type myCustomStruct
i am filling it in the inspector
the issue is that if later i edit my struct in my script (name, parameters, remove/add), the array/struct resets
is there a way to prevent this lose ?
the solution would be filling the array directly in the script, but i would like to avoid that
well apparently its only renaming the var of the struct that resets the values in the inspector (which is normal)
I think you could use the FormlySerializedAs attribute to fix this. Im not really sure what you're talking about for the other issues like parameters
Quick Question:
Is it possible to disable/enable Character Controllers for my Third Person Controller at will, (for instance, when entering/exiting a certain trigger), in the code?
perfect, ty
absolutely, .enabled = true or false
- When i use the graphics api to draw different meshes with the same material within a single frame, will it all go in one batch?
What graphics API specifically?
i would like to draw stuff with gizmo, the issue is, i can only use Gizmos methods in specific methods (ie: OnDrawGizmosSelected)
how can i decie in my code "when" i want to draw ?
example:
lets say i have a loop iterating 10 times, with a 1s delay, and at the end of each delay i draw 1 sphere
how would this be done ?
cross "method" communication
If you use the same material multiple times in a row, it should only be one SetPass call, which is the expensive part of the draw call.
I am trying to write an editor script to generate textures of prefab previews and then stroe their references into a scriptable object.
File.WriteAllBytes(filePath, tex.EncodeToPNG());
var preview = (Texture2D)AssetDatabase.LoadAssetAtPath(filePath, typeof(Texture2D));
building.preview = preview;
The texture gets created but the preview returns null for some reason. Any tips?
just creating the file does not create an Asset. you need to Import it before use
I did update the code as such but im still getting the same issue. And the textures seem to randomly disappear sometimes not sure why
var tex = AssetPreview.GetAssetPreview(building.prefab);
var previewImageName = building.building + "_preview";
string filePath = Path.Combine(previewImagePath, previewImageName + ".png");
File.WriteAllBytes(filePath, tex.EncodeToPNG());
AssetDatabase.ImportAsset(filePath);
AssetDatabase.Refresh();
var preview = (Texture2D)AssetDatabase.LoadAssetAtPath(filePath, typeof(Texture2D));
building.preview = preview;
try adding a .Save after the Import
I just noticed a warning that my path is invalid
which is odd because it was fine for the WriteAllBytes
that wont help
LoadASsetAtPath maybe has an issue with combining "\" and "/" in one path
what is your path?
Invalid AssetDatabase path: C:/redacted/Repositories/redacted/Assets\ScriptableObjects/Buildings Tiles/Previews\Watermill_preview.png. Use path relative to the project folder.
This is my path now
It manages to load the asset but Im still getting the warning O_O
ah nevermind my bad
Thanks for help @knotty sun !
could you explain a bit more ? i dont really understand what you mean by this
public void Update(){
load data
i want lateupdate to process
}
public void LateUpdate(){
if(update want me to run){
}
}
```how to do that
well, i dont see the usecase, but here is my guess:
string _data;
bool canUpdateProceed = false;
private void Update()
{
_data = "its me ";
canUpdateProceed = true;
}
private void LateUpdate()
{
if (canUpdateProceed ) {
_data += "mario";
}
}
//after the LateUpdate you will have "its me mario", since LateUpdate is called after Update
edited because you wanted update want me to run
yes
if after you load the data, you always want LateUpdate to proceed, you dont need the bool, since LateUpdate is ALWAYS called after Update
OnDrawGizmos is called once per update cycle
relying on execution order sounds like a bad idea, make a queue system instead
wait, are you answering my question, or was this a question of you ?
im lost
you want your ondrawgizmos draw something once some conditions in other method was reach
oh sorry i thought you were asking a question for yourself, the how to do that got me
well technically yes, this is what i will have to do
this is annoying because i will have to create multiple bools, for each specific case
a more general way to solve this is to implement queue system as slimstv have said, you load the command in other method that in ondrawgizmos you dequeue all stored commands
okay, how do you "load a command" then dequeue ?
why can't I add 2 strings together?
[StructLayout(LayoutKind.Explicit)]
public struct command{
enum command_type;
[FieldOffset(0)]public command_type type;
[FieldOffset(8)]public type1 data_for_command1;
[FieldOffset(8)]public type2 data_for_command2;
[FieldOffset(8)]public type3 data_for_command3;
.......
}
```i would do this, others will suggest you having an interface
```cs
public interface IDraw{
draw();
}
public DrawBox():IDraw{
Gizmos.DrawCube(XXX);
}
code[0] is not string, it is char
oh okay so it does work