#archived-code-general
1 messages · Page 350 of 1
Create a static "Tags" class or an enum and put all your Tags in there, if you end up changing one you just change the string in that one and not 15 places in the Code
Any idea for the localized int->string problem? For example, in English a 3 would be "3", but in Arabic it will be ۳. I'm sure Unity's localization has an easy way of achieving this but I can't find anything except for the inconvenient solution I showed earlier
Cast to string, have translations for the strings
That only helps within code, which can still get out of sync with your tags in editor.
Yes it can but its miles better than having your code littered with magic strings
As for inspector, once I am home I can look for the custom inspector I found some months ago that actually gives you a dropdown, still doesnt help you when changing a Tag though
Just don't use tags 😁
Yes, the conventional wisdom is that instead of trying to use all the tricks to make a fundamentally flawed feature less flawed, it might be better off to just use something different.
Will need a CultureInfo for that. Couldn't find any API in the localization system that gives us that, according to our currently selected locale
Int to string should be a very trivial task for a localization system, I don't know why Unity's makes it hard (or maybe i just haven't found the easy way yet)
for new readers, i mean a
3to "3" or "۳" depending on the locale. A 1500.5 to "1,500.5" or "۱،۵۰۰/۵"
Oh you even want decimal conversion and stuff, well I guess someone will have had that problem in the past and you should crawl github for C# solutions. This one sounds like such a general problem that there has to be a solution
https://stackoverflow.com/a/47323966
Or I guess unity has other ways to get a country code
I'm trying to implement a "shelf" system where items will be instantiated onto set positions. I'm having trouble figuring out how to account for different rotations. Any ideas on how I could make this work on more than just one axis?
Seems like you just need to instantiate them with the shelf's rotation, no?
or maybe rather their container object? 🤔
When I do that this is the result. I'm no good at the math aspects but it seems like the problem is in the position rather than the rotation. Like I want to find the position using the rotation of the container but not sure how
Ah sure... What's the code look like?
boundsX/Z --- The minimum bounds of the BoxCollider of the container
capacityX/Z --- The total number of items that can fit in the shelf X/Z axis (This is calculated in another method but is working as intended)
paddingX/Z --- The padding between each item
itemSizeX/Z --- The unit size of the item on the shelf
float posX = boundsX + (itemCount / capacityZ * itemSizeX)+(itemCount / capacityZ * paddingX) + (itemSizeX/2) + paddingX;
float posZ = boundsZ + (itemCount % capacityZ * itemSizeZ)+(itemCount % capacityZ * paddingZ) + (itemSizeZ/2) + paddingZ;
Vector3 pos = new Vector3(posX, containerHeights, posZ);
GameObject go = Instantiate(items.gameObject, pos, transform.rotation, transform);
It's sloppy so lmk if there are any confusing bits 😅
is there a way to have 2 event systems with completely separate gameobjects that are interactable? I have 2 event systems in my game that I'm toggling between but it's possible to select the old things still when the new event system is active since the new event system is letting the user interact with the other gameobjects
So I think the issue is that that code works entirely in world space, so when you position the item relative to the boundsX/boundsZ offsets, it does so on the global axes.
I think the solution might be to run your local positions through like transform.TransformPoint() before adding the bounds in, so maybe like...
Ah wait... bounds is already local. I am very rusty 👀
Try
Instantiate(items.gameObject, transform.TransformPoint(pos), transform.rotation, transform)
That is looking better, I just need to modify the code to find the position which shouldn't be too bad. I'll tinker around and respond, thanks for the lead
Yeah, sorry it wasn't terribly accurate 😅
Double check that the bounds variables are in local space!
I am incredibly confused by an issue i'm having on this script.
https://hastebin.com/share/lezaculiko.csharp
I got this script, on Awake i'm getting characterBody and storing it in a Property, however, if i use the ToggleCombat context menu, it throws a null reference exception on line 20.
What could cause the property to null itself for apparently no reason? using cross referencing shows that the only two things interacting with the proeprty is the setting of the value and the method call
Awake is getting called according to me breakpoint debugging, but if i put a breakpoint on the property itself nothing happens (the breakpoint isnt getting hit)
how to fix that
using System.Collections;
using UnityEngine;
using UnityEngine.UIElements;
public class SheepController : MonoBehaviour
{
public Transform Dog;
private float speed = 3f;
private float distance = 2.5f;
private Animator animator;
public LayerMask hitlayer;
void Update()
{
Vector3 origin = transform.position;
Vector3 Direction = Dog.transform.position - origin;
Dog = GameObject.FindGameObjectWithTag("Dog").GetComponent<Transform>();
animator = GetComponent<Animator>();
RaycastHit hit;
if (Physics.Raycast(origin, Direction, out hit, distance, hitlayer))
{
animator.Play("Run");
Quaternion targetRotation = Quaternion.LookRotation(-Direction);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 100);
transform.Translate(-Direction * speed * Time.deltaTime, Space.World);
}
}
}
characterBody = GetComponent<CharacterBody>();```
GetComponent could return null if such a component doesn't exist
or
`ToggleCombat()` could be getting called before Awake runs (or perhaps Awake never runs if you're calling it on a prefab or something)
Can you show the full stack trace of your error?
how to fix what?
fix sheep jumping out of the map
Move your sheep via physics instead of blindly teleporting it via the Transform.
btw .GetComponent<Transform>(); is never necessary, you can just do .transform
hold up i think i fixed it?
how to move via physics
With a Rigidbody
Hi, I've got a question, I have a game with levels and I have an editor inside the unity editor to make them but I don't know where to save them (I don't want/can't save them in different scenes etc...). I want to save them in a json (it's actually just some lists of points), problem is idk how to create a json file inside of the assets folder neither how to access it (the path), how do I do that? Or is there a better way than json to save lists of vector2D/bools/int
Ok ive almost got it but cannot figure out how to get the unrotated bounds on the BoxCollider
Ahhh right. Hmm hmm... Are boundsX/Z just calculated from like collider.center - collider.size / 2?
or collider.bounds.min?
the latter
I know this might be a bit simplistic thinking but if you are having problems placing objects onto the rotated shelf why not unrotate it, place the objects then rotate it back
Okay, so I think they are in world space. If you can switch to the former I believe it should just work. Otherwise you'll need to add them to the position after it's transform.TransformPoint()'d rather than before
Mission successful, cheers for the help
So im trying to make a puzzle game where you collect words in the world and once you collect them they go to the "TV' (the place where they will put the puzzle together, which is all in the same scene) once they are in the tv they cans be collected anymore and you are able to drag them around and put the words in specific points on the TV if it is the correct point it will stay if not it will return to the original place inside the TV
What would be the best way to go about this as there will be many different words
what is the specific issue you're having, there are dozens of ways to do this
Okay So i made a scriptable object that i can reuse to have diferent words, and for testing i have 2 different words in my scene and when i collide with one they both get triggerd even though i didnt touch the other one
and was wondering how the best way to go about this structure wise im just getting so confused and turned around on how to get this going :/
Are nuget packages available through the unity package manager? I'm considering converting my external utility library to a package, but I have some dependencies such as DependencyInjection and abstractions, and a few others. The information I've found on the topic is mixed at best. AI seems to thinks it possible, but found a 2020 post that says nuget packages arn't supported.
Nuget isn't supported officially, but you can download the DLLs and import them yourself
Hi, Anyone knows how to set the {Level} variable of a smart string from a script?
Is there a way to get the normal of a face just from OverlapSphere?
Add a local variable in the inspector (bottom of this screenshot), then do stringReference["Level"].value = value
what do you mean by stringReference["Level"].value = value ? from the LocalizedString component?
Looks like no. A workaround is that you shoot a raycast at the colliders returned by overlap
Yes
Hey, I am receiving this weird problem when Im trying to instantiate an object. It does instantiate in the scene, but the object tends to be disabled in the scene when it instantiates. Any reason to why this might be?
Heres the instantiation line of code if needed: equippedItem = Instantiate(selectedItem.heldItem, playerHand);
the heldItem is a GameObject btw
Well it does not exist, neither from LocalizedString or LocalizeStringEvent
Start simple, by that I mean shrink your original object. Look into triggers and how they work, etc.
It does. Look for StringReference
oh and yes, the prefab for it is active as well.
So I simply dont really understand how its instantiating as inactive
Oh apparently something about the network object is causing the problem
I shouldve know that stupid multiplayer is the issue here
m_localizeStringEvent.StringReference["Level"] = new IntVariable { Value = 10 };
This did the trick
Instead of creating a new IntVariable, you can directly set the .Value
Because it's mutable
Not accessible, unfortunately
IntVariable iv = m_localizeStringEvent.StringReference["Level"] as IntVariable;
iv.Value = 10;
anybody maybe know why this isnt working?
What does the error say?
Is ab a Rigidbody2D?
Check out the docs - the error is accurate, there's no way to call it with three arguments
Using a rigidbody would still cause the error. You are passing three random numbers in
You should pass in the Vector it is expecting
You're right. I always forget that it has that second overload. ArticulatedBody does not though haha.
yeah i just seemed to figured it out Loll
Hi, I'm having some problems with the DontDestroyOnLoad objects, i'm trying to get the component "Unit" that is in: party -> Teammate1 -> Unit, but when I assign it, it doesn't refer to the actual object, I think it is creating a new "unit" component to reference
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
i think the problem is in line 20-24, but I can't find a way to fix it
Trying to get a bone (selected) to face towards player. However, due to the fact the bone has a weird axis layout (Y is forwards), I am having difficulty trying to get the code to work.
var playerDerivative = (PlayerController.instance.transform.position - headTransform.Value.position).normalized;
var rot = Quaternion.LookRotation(playerDerivative, Vector3.forward); //Since Z is up for the bone.
headTransform.Value.rotation = rot;
Am I doing anything wrong?
Hey there, I'm wanting to implement a way for the player to add custom scripts to weapons, so when they attach the script to the ScriptableObject's variable, instead of running on built-in code it'll instead run the custom code, however, The code WILL have to be static (Although I could always just make the script attach to the player and then remove itself when switching weapons), and I know that you can't use the monobehaviour itself in the code, as you have to future proof for pretty much every class name. Anyway I can do this?
You want your players to write custom scripts?
If they so wish, yes, specifically for weapons.
You know how the Source engine has specific scripts for weapons? Such as physcannon (Gravity Gun), something like that, although I'm hoping for a way to be able to reference the script as a variable, and either it'll add the component to the player/npc when it is equipped, or will call static functions
It would work like:
(In the ScriptableObject)
public Script Weapon_CustomScript = null; (I know that Script is nonsense, just psuedocode)
(Custom Script)
{
public static void Weapon_PrimaryFire(GameObject origin)
{
Handler_Gamehandler.Game_GetGamehandler().Astro_WriteToConsole(origin.name + " Primary Fire");
}
public static void Weapon_SecondaryFire(GameObject origin)
{
Handler_Gamehandler.Game_GetGamehandler().Astro_WriteToConsole(origin.name + " Secondary Fire");
}
}```
When the player runs the primary or secondary fire, it would call the function, regardless of class name
Anyway, if that’s what you want you should embed an interpreted scripting language with a limited and well curated API for game functionality it can use.
Stuff like that is often done with Lua.
Ah, I see
Is there a way to have a variable be set to a script? I can't seem to find it, and I'm not sure if it's a niche thing or not
Very niche
Technically you can allow a player to call any method on any GameObjects that is loaded in the game via SendMessage()
Oh, I'm well aware, although some people have said that is a very bad idea
I'm more or less concerned how I can get a script to be a variable, so I can put the script unto the player/npc
it is
Guys i have a quick wuestion, im making a tank game and im going to start working on the tech tree now, basically like the one in warthunder in which you can unlock tanks etc. I was wondering if this should be done with normal script or is it better if i do it with ScriptableObject
you can't store a script in a variable, but you can add a component to a gameobject through specifying the class (type). and you can store that type in a variable.
Either one works, but it's really just a matter of do you want to assign these in editor (with scriptable object or monobehaviour) or by code (plain c# class).
For something like a skill tree, I cant imagine you'd need to be serializing much
technically you could compile a script from source at runtime, load that and run it, but idk how unity responds to that kind of thing. In any case its not a good idea.
Alright, thanks :))
Well, that wouldn't fit what I would be looking for, unfortunately...
I was hoping that it would be as easy as assigning a variable to the variable, and that static functions would be called
If you're referring to the interpreted script that the player wrote, in the worst case you can just pass the code string. Or, better, a reference to an object that contains the code string.
Yes, the custom made script is what I'm reffering too
Anyone able to help?
i'd say if you can't embed/build a separate runtime for that kind of thing (lisp, lua, custom DSL etc.) drop the idea
I found MonoScript, but there doesn't seem to be a way to actually call functions from it
you have to build that hook for function calls yourself. You can use C#'s reflection features to access/call pretty much anything
Might be easier to reexport the model correctly, or use a proxy empty go to fix the rotation.
Ah, it's a bone... A proxy wouldn't work then.
Ah, I see
You can't just use C# code they wrote as is, you'll need to compile it. That's why Anikki suggested a different interpreted language for it.
Also players exchanging C# scripts with access to native libraries is terrifying 😬
I think I may be a little dum in the head, sorry 😓
I also didn't think of the ramifications of that, either
I just want players to easily mod my game, if they so desire too
But I'm not really sure to implement LUA or other DSL languages
unsupported but might get you some orientation: https://assetstore.unity.com/packages/tools/moonsharp-33776
Honestly, this kind of feature is something stretching to the advanced level. And even if you have long years of experience with unity and coding, it would require a thorough research. Not something you can just get an answer lightly on discord.
I was hoping it would, but thank you for your help regardless
I'm also... intermediate, to be honest
Although, I DO have addons working (Loading scenes/maps, ScriptableObjects, etc), just custom scripts would be awesome you know?
its awesome but also extremely powerful, hence the complications
It's not impossible, you just need to do proper research.
if unity were written in python or javascript this kind of thing would be trivial, but you'd also have only 1% of the performance
can you serialise with a different number than the actual property?
that makes no sense
depening on your serializer your can
you can put a custom label on anything with odin
doesn't change the serialization though
LabelText is used to change the labels of properties.
Use this if you want a different label than the name of the property.
this is a bad name btw, you should generally spell out what a thing is, not abbreviate, this then fixes the uglyness too.
people know how to mod enough that you dont have to do anything special. You could just make it easy to attach new scripts and leave a general tutorial on how you created the weapon objects.
People will probably mod it faster than you can make logic for them to mod it with
Yeah, alright, thank you!
As an example, each weapon is a ScriptableObject called ScriptObject_Weapon
also worth considering that unity is in no way designed to be a framework for making another game-engine or any kind of application that deals with data ingress. You can build all that yourself, but you get no help from unity. Those who tried (that i'm aware of) have abandoned the approach in their v2 if they have survived. Mod "support" extends only to assets, configuration and interpreted scripts (if you provide the runtime for them).
I don't know how. Every guide on "exporting models for blender" tells me to keep bone axis settings the same.
afaik I am exporting this model correctly.
Hmm... Well one thing you could do, is get the required rotation first and then rotate your bone by that rotation, instead of using look rotation.
Like, the issue is that you need to know the offset of the bone to do any correct rotation taking the offset into account.
If you know that it's up is actually forward, then you could just do transform.up = direction instead of messing with quaternions.
is that screenshot after your code has ran? or is that how it looks in the prefab?
If it is an issue with the model try stuff written here. This person helped me i never had an issue exporting after #🔀┃art-asset-workflow message
It could even be that the model/rigging wasnt setup correctly
for some reason my audio source called "Pop" isnt playing but every other sound is playing. its supposed to play when i build something or drop a human into the scene
or some event driven too
Hey, so, how can I rename a class without losing the variables located within?
For example, I hate that my current class is called Entity_Transition, and want to change the #C script and class to Entity_EventChangeMap
However, I am worried (Because I have done this before) that when I do, I'll lose a lot of progress cause I use this a lot, can anyone help me out here?
F2
you wont lose the vars but might reset the values. I dont remember lol
Oh, I meant the values on a gameobject
Git backup your project. Take a picture of your settings before modification or write a script to save/load your scene settings.
i dont think ive ever lost values when i renamed a script. Thats even when I rename it entirely in visual studio, while apparently you're supposed to rename it first in unity
but yea not like anything can go wrong if you use version control
I use Github GIT
do note the two are not related
github just hosts GIT repositories
but there are others, bitbucket, gitlab etc..
If I wanted to store instances of distinct classes which share a common interface, key them by type, and expose an API similar to GetComponent<T>(), would this be a remotely reasonable means to accomplish it?
private Dictionary<System.Type, SystemController> _systems = new();
public void AddSystem<T>(T system) where T : SystemController {
_systems.Add(typeof(T), system);
}
public T GetSystem<T>() where T : SystemController {
if (_systems.TryGetValue(typeof(T), out SystemController system))
return (T)system;
return null;
}
I guess they don't necessarily need to be keyed by type - I just found myself reaching for something akin to a JavaScript Symbol
What does JS symbol do in this use case? JS symbol is essentially just a pointer that can be used as property key, I don't see how that's related.
Probably only through my own ineptitude and unfamiliarity with generics 😁
Maybe more succinctly: I want to store distinct instances of the classes, and did not want to index them via some member on the instances which might only exist for the purpose of indexing them. So indexing them by type seemed to make a lot of sense in my head
I just mildly fear I stumbled into some poor pattern or implementation. This is me mostly just flailing around a bit
Yeah I just don't see how that's related to JS symbols, but otherwise that code seems fine.
Thank you I appreciate it!
JS symbol really just is a reference type, so if you want something like one, it's just new object().
Ahhh that's interesting. Sure, that makes sense
JS symbol is the same too, you could just do const myKey = {} and that guarantees uniqueness. The only reason JS symbol has to be invented is because you can't use that as a key (so you can't do dict[myKey] = 42)
is unity's mesh RecalculateNormals() method on github? need to see how they calculate it since mine isn't correct
You are totally right. I don't touch symbols often - but I was playing with them for work earlier today and I think they're maybe still haunting my brain and winding up in places they shouldn't be. You are right - a Symbol has no relevance here 👍
I have a bit more of an abstract problem, but I'm trying to figure out how I should structure my combat in my code.
So I have an actor who has the ability to attack with either their fist or with a weapon, and there are different types of weapons with different animations, combos, etc. What is responsible for doing the damage? The sword object itself, a combat script, the receiving party.. etc
it's very confusing
I'm looking not for a direct answer for this exact question but maybe some pattern/design solution commonly used for this problem
Hey guys
Why my Backflip not working?
Well, it's working
but only rarely
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
This is a prototype, ignore the crooked code
I mean, It's not working
Hello
I have this structure
[Serializable]
public struct RelationshipConfigData
{
public RelationshipStatusConfigData[] Statuses;
public int pointsPerMessage;
public int pointsPerMessageLike;
#if UNITY_EDITOR
[Button]
public void CopyAsJson() => CopyJsonUtility.CopyInBuffer(this);
[Button]
public void PasteJson() => CopyJsonUtility.FromBuffer(ref this);
#endif
and there is such json
{
"Statuses": [
{
"id": "status_strangers",
"name": "Strangers",
"initialOpened": true,
"MaxPoints": 75,
"transactionID": "status_default"
},
{
"id": "status_friends",
"name": "Friends",
"initialOpened": false,
"MaxPoints": 75,
"transactionID": "status_friends"
}
],
"pointsPerMessage": 1,
"pointsPerMessageLike": 2
}
I'm trying to convert this json into an object via
var result = JsonConvert.DeserializeObject<T>(jsonData);
but an error occurs on the device
ExecutionEngineException: Attempting to call method 'System.Collections.Generic.List1[[RelationshipStatusConfigData, Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]::.cctor' for which no ahead of time (AOT) code was generated.
some other configs converted normally and there were no problems, what’s wrong?
show !code for RelationshipStatusConfigData
📃 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.
[Serializable]
public struct RelationshipStatusConfigData
{
public string id;
public string name;
public bool initialOpened;
public int MaxPoints;
[TransactionID(TransactionTypeConst.Status)]
public string transactionID;
}
could this be due to the fact that there is an array of RelationshipStatusConfigData and not a list?
Yes, that confused me. In json there is no difference between an array and a list so I'm somewhat confused why it is trying to build a list
why can this happen at all? Literally in another branch everything worked with an array
I have no idea, I dont do json but your code and data look fine.
one thing you could try is to initialize the array so it is not null
I am presuming this is Newtonsoft Json
yes
I know why it is throwing the error but I have no idea how it gets that far. The easy fix would be to change the array to a list but that should not be necessary
I found this solution, but I still don’t understand what this is connected with, I’ll try it
It might be worth updating the version of Unity or the version of newtonsoft itself
yeah it is the=managed code stripping.
simply adding a List<RelationshipStatusConfigData> somewhere will solve it.
I'm guessing JsonConvert first builds a list then converts the List to an array which would make sense because it cannot know the size of the array whilst it is parsing the data file
is it enough to add it above my array?
tbh I would add this to your RelationshipConfigData struct
[Preserve]
static List<RelationshipStatusConfigData> ToList() { return new List<RelationshipStatusConfigData>(); }
where should I call this?
you don't that is the whole point
in one of the projects I also used such a thing
just by having the code with preserve will ensure the the List<RelationshipStatusConfigData> constructor will exist at runtime
sorry that code should be RelationshipStatusConfigData
i will try to use this
you still need the [Preserve] attribute
this is all?
yep
can i set custom frustum culling range in Graphics.Drawmesh function?? I want to render a lot of grass inside a custom range...but not inside the whole frustum range of the camera..what should i do?
Well, I don't think you should call Graphics.DrawMesh for each grass mesh individually, instead you should call one of the instanced methods to do it much faster
i couldn't get it... can you explain a bit?
Each time you call Graphics.DrawMesh, it's basically a draw call which are quite slow if you call it thousands of times. Instead you should pack your data to ComputeBuffers/Textures and render all the grass at once with Graphics.DrawMeshInstancedIndirect or similar method. It's bit harder to set up but it's definitely worth the time to drastically improve the performance. The problem with the instanced methods is that they don't do any frustum culling at all which takes us back to the original question. Since there's no frustum culling happening by unity, you must implement the frustum culling yourself and therefore you can do your own range stuff there.
do you have any idea on how to do that custom frustum culling thing??
You basically must take all your grass positions and put them in a ComputeBuffer and use Compute Shader to produce a list of grass positions to render. I assume you are trying to create grass system that's able to draw thousands and thousands of grass meshes am I right?
yeah! i want to render a lot of grass meshes
Then Graphics.DrawMesh won't work as I said. There's also a lot of raedy to use grass systems available if you don't have the time and effort to put in one
yeah...looks like a long way to go...
I read online that says that unity uses the Mono C# compiler, produces Bytecode(IL + metadata) then uses the Mono Runtime to translate that into the platform specific Machine Code
correct
And the reason why unity is able to export cross platform is because of Mono's role in the above sentence?
indeed
I'm also confused on if the compiler for the C# scripts matter in terms of cross platform ability
if we have two different compilers and then feed the bytecode into mono runtime will they both be able to be translated into platform specific machine code?
The blog post I read said that unity uses Mono C# compiler for the scripts, but I was wondering if this was necessary
yes it does because Mono .Net IL is not the same as MS .Net IL so if you compiled using MS .Net (at least for the versions Unity uses) it may cause problems cross platform
I see
Is it because Mono .Net libraries(I'm under the impression that .Net is a giant conglomerate of libraries) might be diifferent to MS.Net libraries?
exactly
So then is the reason mono developed because MS.net didn't have cross platform in mind so they decided to translate that functionality so to speak themselves?
Do the two follow some sort of agreed upon guideline so the .net base functionalities are somewhat similar, or do they now do their own things but develop under the same ".net" name
that is basically correct, then MS reabsorbed Mono and renamed it Xamarin To bring some kind of normalization but there are still many differences. When (if) Unity eventually migrate to .Net 7 + then all of this should go away
I've also read about this IL2CPP that supposedly came around 2018 and I was wondeirng if it ran on the same .net libraries that Mono provided, or is this another rewrite situation?
Oh nvm it stands for intermediate language to Cpp
Does that mean instead of mono runtime it uses IL2CPP instead, but still uses mono libraries during compilation?
IL2CPP does exactly what it says, It convers IL into C++ source and then compiles it into native binary, this means that it is not cross pllatform
This means that IL2CPP compiles into native library ahead of time(AOT)? And that this only works on select platforms
exactly
So if I'm gettin gthis correctly, IL2CPP only works on platforms that CPP is able to compile into native binary
or rather platforms that use native binary
That's basically any platform out there
which will be all platforms, the important thing is that code compiled for one platform will not run on a different one
Everything runs on C++ or C
Ahhh I see
I had no idea
To be precise, C/C++ compiles to almost any platform native code
yes, to be more precise, platform specific native code, which is why it cannot be cross-platform
Ah that makes much more sense
I did a little reading just now and my interpretation of the mono vs il2cpp is as follows:
- Mono is cross platform because it translates into machine code on the fly from ByteCode(JIT)
- IL2CPP is ahead of itme compileation which because native machine code is different, is not cross platform, but since CPP can target any native machine code you can export to any platform
Which makes me wonder if cross-platform means strictly that you can run the smae piece of code on different platforms
To be fair, "not cross-platform" doesn't really matter here. It's not like you can run a mono build for a specific platform on any other platform.
That's what I was wondering as well
This 'you can export to any platform' is the wrong concept. you do not 'export' you 'build to'
As in building to a specific platform's native code?
yes
Mono and dotnet are cross-platform as frameworks. Meaning that their API is able to be compiled to any supported platform and is usually guaranteed to work the same way. On the other hand, if you're building a C++ app, there would be a lot of platform specific code, platform specific libraries, etc...
Gotcha
Unity takes care of that for you regardless of whether you build a mono or il2cpp, although there are some limitations
I'll look into what exeactly this platform specificness is... my confusion comes from the fact that different platforms have different native languages and that handling conversion from high level languages to this native language would have to be handled anyways regardless of cpp or mono?
I've read that ios supposedly does not support JIT so mono can't be used or something
If you look at the workflows it's quite simple
Source->.Net Compiler->IL->.Net Runtime->OS->bare metal
or
Source->C++ compiler->native binary->OS->bare metal
Platforms don't have native languages. It's more correct to say that they have their own CPU instructions. When you compile a C++ build to native language it means constructing these instructions. Same when dotnet is compiling JIT.
IOS has XCode which, basically functions the same way
So in IL2CPP's case would it be
Source -> compiler -> IL ->(via il2cpp) C++ source -> native bin
or is this a wrong interpretation
that is correct
build to = translate to target instruction set commands?
Yes. Basically.
is it possible to make Graphics.DrawMeshIntanced objects support lightprobes by any means?
not happy with the word translate because a compiler does a great deal more than that
I guess if you can bind the required data/resources manually and your shader uses it correctly.
would this be a good time to read up on compilers then?
Any uhh recommended sources for this type of stuff
If you're interested. I wouldn't say it's absolutely necessary for a gamedev.
If anything, I'd rather stay a way from low level stuff and let smarter people deal with it
I honsetly would not know, I grew up with stuff as it was being developed
Roger that
At least now I somewhat know how unity cross platform works
Thank you both for this incredibly long dicussion, I definitely understand this much more than I did before
Really appreciate it
thats not just Unity cross platform, the same basic structures are true for most modern languages like Java, JavaScript and Python
in fact C and C++ are somewhat on an anachronism as they compile to native code, not many modern languages do
is this a bad thing?
only in terms of performance, C and C++ will always out perform anything else
Gotcha
the closer you are to the metal, the faster the code will run, this is why we still write device drivers in assembly code
Thank you for the explanations
Hi. One question, is it normal that using Invoke(nameof(DoSomething),0); is faster than doing DoSomething();? Like, what are the downsides of using Invoke then?
It's significantly slower
Invoke can never be faster than a direct method call
then idk what I'm doing wrong with my setup but it is telling me that it is faster. Let me see if I can do it again and show it
What kind of "setup" do you have?
And what's telling you that it's faster?
The setup:
public class CodeTesting : MonoBehaviour
{
public int iterations = 10000;
[Button]
public void Iterate()
{
for (int i = 0; i < iterations; i++)
{
Invoke(nameof(DoSomething),0);
//DoSomething();
}
}
public void DoSomething()
{
Debug.Log("smth");
}
}
profiler
That is never going to work as a test case to profile
the likely reason that there's a difference is because the stack has been thrown away when you use Invoke, so the overhead of extracting the stack for the log is lower
it's got absolutely nothing to do with how you're calling the method
Why does my layer mask make this check box ignore all layers and not just layer 10? 😕
bool isColliding = Physics.CheckBox(boxCenterWS, wheelContactArea * 0.5f, wheelParent.rotation, 10);
because layer 10 is NOT LayerMask 10
The bit shift solution - although you should just have a field and set the layer from the inspector 1 << 10
I did try GetMask and NameToLayer without much success earlier
1 << 10
This did the trick though
Create a field:cs [SerializeField] LayerMask layerToIgnore;//Set the layer from the inspector.Apply/use the value:cs bool isColliding = Physics.CheckBox(boxCenterWS, wheelContactArea * 0.5f, wheelParent.rotation, layerToIgnore);
As my link says, NameToLayer would also be invalid
Hey does anyone know how to stop 2dynamic rb2d from pushin each other
What should they do instead?
act like walls
so when walking into each other they both stop the other
while not being pushed backwards
Sounds like you'll have to implement some custom edge cases for non static colliders not wanting to treat each other as dynamic objects - modifying drag could probably yield the behavior you'd want but might create other unwanted issues.
for example?
Might have to do something like raycasting towards it and then manually negating the velocity
So if touching other dynamic body:
Velocity = 0, current, 0
This can work but after touching a body they stay inside each other meaning that the velocity gets set to 0 only once at the beginning of the collision afterwards the player can continue to try to move inside the enemies collider which will in turn push the enemy, i dont know if this is what will actually happen though
what about negative velocity where it pushes them away from eachother?
what i mean is that lets say theres an enemy staying still the player can run into the enemy the enemies velocity will be the sames as the players( same direction) the player will stop moving after hitting the enemy the enemy wont get pushed since we set the velocity to 0 at the start of the collision afterwards the player can decide to move again and this will push the enemy, if i make it so if the enemy checks constantly if a collision is happening so i can set the velocity 0 this will make the enemy not get pushed even after the player moves again after the initial collision but the enemy wont be able to move itself out unless the player moves out of the collision as the velocity is being set to 0 constantly
would it work to just make them heavier?
Increasing drag?
the player might not push the enemy but the enemy can push the player and the enemy can push another enemy
yep
ive tried bounciness and friction to 0 as well
on the colliders
Well all of those things are completely unrelated, so its not like itd do anything
Unless you set the velocity every fixedupdate to what you want for both objects, you cant really do what you want using unitys rigidbody.
this might be useful? https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131
its not an ideal solution ik
the game im trying to make is 2d
oh idk if it supports 2D
yeah this is why im stuck
the only thing that has kinda worked
is having enemies and the player have a child object with rigidbody2d set as kinematic with continues collision detection
do you actually need a dynamic rigidbody on the player
and having the collider of that child object bigger than the enemies or players collider
ive asked my self this question a lot xD
but yea i do
why exactly?
You can just make your own kinematic rb solution for 2d. These other solutions wont work
You simply cannot have an active rb to achieve what you want. If you use it, it will be pushed around by other things with velocity, end of story
trying to make a 2d souls like and pushing the enemies or having no collision between enemies just feels wrong to me
i want it to be just like the games where the player can run into an enemy and nothing happens
or vice versa
yea
how about using a charactercontroller?
only is for 3d
doesnt work for 2d
is it?
there are many tutorials out there for simple 2d movement
yea but all that ive seen are just no collision between enemies
or custom collision detection using a kinematic rb
thats what im thinking
of doing rn
those tutorials would go through custom collision detection. of course theres no collision detection if you arent using unitys physics, which you cant in this case
But really you can just cast to check if anythings in the way, and not move into the object. If platforms/other stuff can move into your character, then you'd need to depentrate somehow
the not move into the object would work
but lets say i have a enemy that will lunge at the player
i need the enemy to have collision so that when it hits the player it stops
but is able to not be pushed
etc
You can still check with physics casts to see if the enemy should stop during this lunge, and if you arent using a rb then it cant be pushed anyways
yea maybe
but thats the aproach im leaning towards the most
i just was trying to see if there is another way
thats simpler
You could try what i said at the start, about setting the velocity every single fixed update to what you want. But im not sure if theres any catches with that
and it'll still do its own depenetration
The player should definitely be kinematic.
Use Raycast/Boxcast to limit the movement.
what about the enemies
i need them to collider with other enemies and the player and not get pushed around or push others
would i need to raycast as well for them
The same, if you do not want them to move when they are colliding.
You can do all of them manually.
Thats what im trying to avoid xD
i was trying to see if theres a few options i can set and be done with it
xD
Then buy an asset that does it.
I dont know if there is any
honestly making your own 2d character controller should be fairly easy
3d is a different story
You can always try to use multiple layer but I am not sure how it would behave
This is what ill probably will end up doing
this is the same suggestion ive been saying most of the time, and same as what simferoce is saying
im 90% sure there are are already 2D character controllers available on github too
i'd be shocked if there was nothing available like what you want
Usually, I like to only push enemies outward instead of preventing the collision
In other words, players/enemies/enemies does not interact
just opened to search xDDD
I need advice, I'm making a card game and have cards stored as ScriptableObjects (CardSO) which have various effects also stored as ScriptableObjects (CardEffect).
And I want to have those effects to have their own little variables that can be affected on runtime by either their own effect or another card's, now currently I'm creating a separate MonoBehaviour script for every different effect (e.g.: the AddRequiredComponents in DamageTargets)
which can of course easily pile up a ton of different MonoBehaviours just for one card, and therein lies the problem.
How do I restructure this so that I don't have to instantiate a new MB for every effect without using ScriptableObject.CreateInstance() ?
experience of other people in this server with making a card-game (with arbitrary rules, not just poker) boil down to: it is very difficult to make the rules for these cards in a statically typed, compiled language and regardless of how you reach your goal, you will have created what basically amounts to a ill-conceived and badly maintained domain specific language. Their advice is it embrace that fact and just use an interpreted, lisp-/lua-like language from the start to represent your card-rules. for reference (never used these libraries) -> https://sharpscript.net/lisp/unity -> https://www.moonsharp.org/
reason being that declarative rules generally do not work out in the end and you will eventually want to add procedural code to them to keep things simple.
I see, that's sort of what I expected. Though this is mostly a practice project for me to learn about SOs, so unfortunately I'll probably just go with a janky solution of putting all the 'effect variables' into the Card's MonoBehaviour.
Nonetheless thank you for your help
Have an SO that contains a list of all the effects you want on a particular item?
I think the advice "just use a different language" is an odd approach given this is a unity discord lol
But he presents a good point to the advantages of functional languages
Kinda reminds me of Greenspun's tenth rule
yes I do have a list of CardEffect in the CardSO , so a list of ScriptableObjects inside of the ScriptableObject
the thing is I have some specific variables inside those CardEffect that I want changed on runtime, so I either need to use ScriptableObject.CreateInstance, make a MonoBehaviour with the same variables, or just move them to the Card's MonoBehaviour
the advice is not to use a different language its an advice about architecture and recognizing what the actual problem is one wants to solve. Its also not about "functional" languages but about a language where code is also data and can be manipulated while executing. Lisp in particular is excellent for situations where you have to dynamically invent a custom world in which to operate in while being extremely simple from a syntax/operator perspective.
Hey, does jobs and burst compiler work in browser games?
Is there a way to make the screen darker besides a specific rectangle? I guess it should be something with UI mask maybe? I'm thinking about some inverted mask
or cut out a part of an UI image
Supported platforms
Burst is supporting the following platforms for standalone players:Windows
UWP
MacOS
Linux
Switch
Xbox One
Xbox Series
PS4
PS5
Android
iOS
Thanks I couldn't find it in docs.
You can use SerializedReference instead of MonoBehaviour. Also, I usually use the Factory Pattern for such situation.
public class DamageCardEffect : CardEffect
{
public class Effect : CardEffect.Effect
{
//Actual runtime behaviour
}
public CardEffect Build() { ... }
}
public class CardDefinition
{
[SerializeReference]
public List<CardEffect> effects;
public Card Build()
{
foreach(CardEffect effect in effects)
effect.Build();
//Add other effect from other sources
return card;
}
}
Sorry if I misread your needs, but have you heard of the idea of Data Transfer Objects (DTO).
It is when you have a class that you acts as an intermediate layer as a go between for objects needing to read, write, move, or edit data.
In Unity some people use DTO with scriptable objects.
Example for an RPG that has crafting. The games items are scriptable objects and you want to have your players enchant weapons and save them, so you need to edit the item's properties of the scriptable object.
What some people do is they use a DTO that reads the initial values of the scriptable object and from there on in runtime edit the properties of the DTO.
So the DTO acts like the runtime data to edit, move, and do anything with.
That would not be a DTO, but you explained what you mean correctly.
Well it is not exactly a DTO, but a false one. There would be more to it for it to be called an actual DTO.
In normal applications DTO are just used to encapsulate dara and transfer it between different systems or layers in the application.
In Unity you can sort of use a fake DTO like a struct, record, or a normal class that inherits from nothing.
You can think of the Scriptable Object as the layer of the game app that contains data like a database and use a fake DTO class that reads the values of a scriptable object and have other runtime classes used that fake DTO for example.
It is useful for the chain broker pattern.
it might be better to think of an SO as the immutable config state of a "thing" and that fake-DTO as its separate mutable state, whether that is bundled into a struct or represented as primitives in multiple lists would not change its nature, but if you call it a (fake)DTO, you force the whole story into OOP think which might actually be counter-productive.
That is 100% true as well. It really depends on how the structure of the scriptable object and the card effects are set up.
For his case I think what @cold parrot mention would be more relevant to my comment. Now that I read more of the previous conversation.
there sadly is just no way to do all this in a nice way.
in theory you can, it can be clean, you can make nice interfaces and algebraic types and higher order functions and all that, but its very impractical.
thats probably one of the reasons why so few card games get made that have non-pattern-based rules.
Honestly it might be a good idea to chart out the flow of how you want a pattern to work in game.
Than see what possibilities you need to work within a contained thought process for and go from there.
I found when working with systems that require a lot of extendibility, customization, and complex pieces doing something like this helps.
Do note this is a full on Metroidvania character controller for players, NPCs, and enemies so had to zoom in only on a piece of it because it is a chunky boy.
i would add that it makes development much easier if you have a map like this and know exactly what features you actually need. If you don't have such a map, you can easily get stuck in very generic implementations that produce no interesting gameplay. Generic systems also need way more code that does nothing and are way harder to maintain due to that.
Oh yeah, the amount of time I think our team saves by making maps way out paces the time it takes to make them. It gives us a chance to see where we may be overlapping systems or pieces of the project.
Allowing us to clean it up before we even start coding. This helps lower refactor possibilities mid development.
Something I think helps a lot of people out in team situations.
By now I firmly believe that without a ‘map’ you guarantee that the team goes nowhere and with a rigid map you guarantee that you will be building something useless.
Sad, but true words. When it comes to coding and making a map for things some people, including me I admit, might miss the mark sometimes.
Think at this point maps are meant as a way to help visualize the flow of intent for what you are coding and to be able to visualize different pieces that are connected to each other.
Including data being sent from one object to another or calling another objects function.
Maps might be a good thing to think of a guide on an always changing world. It helps get you near your destination and keep on track, but it should never be fully used as a concrete thing that can't be changed.
Through out development change is okay. The importance is learning how to set up code to allow for changes without breaking everything and having to refactor entire classes.
All hail interfaces and abstract implementations as long as they are not over used for that one.
The map also reminds you where you wanted to go, what choices you made and what forks are upcoming. Also allows you to track progress and keeps you moving.
the important thing is to realize where you are and where you can go from there. It’s so easy to dream about the ocean that you forget that right now you need most of all climbing gear.
What I read was mapping is a good objective tracker.
What my mind was thinking SCOPE CREEP SCOPE CREEP in your dreams.
I want to make a jump pad. Normally i would write a script for a jumpPad object where OnTriggerEnter would push the player. However i'm not using a collider or rigidbody for the player (i do everything with raycasts). So how would i approach this issue? I was thinking attaching a trigger collider to player and calling OverlapBox on the jumpPad object.
Is there a reason you arent using a collider/kinematic rb? If you do, you can still use physics functions
I guess i could use a kinematic rigidbody. It wouldnt make much difference performance wise, right?
we're talking about 1 kinematic rb and collider here
i would have to do that for all units in the game in the future
Then for that youd need to profile, comparing rb and colliders to an overlap check for every interaction that can happen with the units. Itd still be 1 overlap check per unit per fixed update
But honestly if your game lags from just kinematic rb and colliders alone, you're probably doing too much
Hey everyone, I am an intermediate unity developer. Made two 2D Games for Android on my own. Also I have made one 3D game by following a tutorial.
I really want to understand how do I proceed further in my game dev journey? Specifically like shall I watch more tutorials , or learn more about C#, or just start making my own original projects (clones as well) without any help?
I just need a little guidance or a basic roadmap so I pave the way properly
Make a simple project on your own
Seek help as you run into problems
Should that be a prototype showing mechanics or a proper game
Also Shall I just stop watching whole long hour tutorials? because I really think that tutorials have wasted my time. Not that those videos were bad, but How I utilised them were pretty dependent
This isnt really something anyone can answer. Make what you want or need to. Do you need to showcase mechanics?
You definitely shouldnt be watching step by step tutorials that make a super specific feature. Most of the time you'll have trouble actually expanding on it. These are the tutorials where they type code on screen in real time.
Generally you should be looking up how to do a concept and try implementing it how you need it
Yup. I literally wasted months into that thinking that it would increase my knowledge. But it made my brain go Auto Pilot mode. This is the time where I actually started learning concepts properly and then trying to apply them in small projects.
Regarding that, I was just asking what all things necessary for a good game programming portfolio?
I cant really answer that myself, this might be more of an industry question though not sure what channel itd go in here. You could look online but at least one general thing I know (not specific to game dev) is that people usually dont look through your code. It's a major hassle to do so and they just wanna see the final product
okayy I understand
while(GameObject.FindWithTag("LevelEnd") != null){
Destroy(GameObject.FindWithTag("LevelEnd"));
}
Any idea of why that would create an infinite loop?
This definitely should be in #💻┃code-beginner
Look at the docs for destroy, it isnt destroyed instantly.
Sorry abt that, idk what are beginner errors and what aren't
If you're a beginner, it likely belongs in the beginner channel
But please cache those objects in an array or something. This hurts to look at
Well this is only for helping me making my levels it won't be part of the final game so it's no big deal
Changed to DestroyImmediate (it also fixed the problem that Destroy() is only effective at runtime and not from the editor)
Do a couple of small gamejams, perhaps?
Input.mousePosition;
Why is this so inaccurate for UI its like pretty far off from the mouse position
it's not inaccurate, it represents the exact position of your mouse on your screen, so 0, 0 is bottom left and 1920, 1080 is top right (assuming that's your resolution).
You are probably not converting it correctly.
depends how you are applying the position. Input.mousePosition is simply Pixel Screen Space, because UI also accounts for Canvas scale
most cases with UI you want to move the anchoredPosition of the rect transform
If it's just generic settings, then it's fine. That's what player prefs is for.
save to file or PlayerPrefs
Unexpected behavior from GridLayout.WorldToCell()
Everytime I write a new thread, the act of typing it all out brings me to a solution....
You all are my rubber ducky.
You are likely better off not using it. If you have to save anything custom you're gonna be writing it to file anyways. Might as well just save everything using the same method, and at least writing to file is easily visible for everyone.
(dont use playerprefs for anything besides maybe options)
i have a script that checks what type of ground the player is on and then plays the footsteps accordingly. the terrain stuff works great, the gameobject stuff not at all, it plays the sound of the terrain underneath the gameobject with collider even though layer name checks out.
does anyone here know why?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
yeah, but to be honest its very inflexible
the benefit to using playerprefs is that its persistent between installations
thats also its downfall, you usually dont want save files to be tied to windows registry
or whatever platform its on
yeah
its more flexible, convenient for you and for the user
you could also argue that for the use case of settings, if you want them to modify settings you could leave them in a plain json file
use json, anything else is extra work thats a pain to replace.
Depends on what you mean by a "file type". If you mean the extension, it doesn't matter at all . You can even have extension less files and that wouldn't affect the contents of the file. Now the contents are up to you, but generally they're either in a text format(like json, xml or just plain text) or binary(which you'd need to know how to interpret otherwise it would just look like a sequence of 0 and 1).
Format!
If you foresee the possibility of format changing and you still need the ability to load older formats, you should also have some way to identify the format version. A common approach is to just have a version field in your content.
Heya Im trying to make my character rotate towards where the mouse is hitting in the scene. I'm using atan2 to calculate the degree to point to and everything works well until I begin to move. The further I move the more innacurate it gets. Any clue why this could ve happening?
This is in update()
//WorldPositionOfRayHit
worldPos = GetMouseLookAtPos(Input.mousePosition);
//Get the degree to face relative to player and ray hit
float targetAngle = Mathf.Atan2(worldPos.x, worldPos.z) * Mathf.Rad2Deg;
//TurnSMoothly
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
//Rotate on y-axis to the degrees given by atan2
transform.rotation = Quaternion.Euler(0f,angle,0f);
public static Vector3 GetMouseLookAtPos(Vector3 mouseScreenPos)
{
RaycastHit hit;
//Cast a ray from mouse to world
Ray ray = Camera.main.ScreenPointToRay(mouseScreenPos);
//If it hits something return the place it hit it
if (Physics.Raycast(ray, out hit))
{
return hit.point;
}
return Vector3.zero;
}
I think that the calculated angle is relative to the world origin rather than the character's position. I believe you just need to subtract the character's position from your worldPos before finding the Atan2
yep that fixed it thanks!
Hello, Im trying to update two different score vairables that are inside of a pause menu. I keep getting NullReferenceExceptions saying that the Object reference not set to an instance of an object even though I have done this. Please help!!!
Make sure you don't have two of those scripts in your scene. Search the script name in your hierarchy.
Legend!!! thank you so much!
Sometimes randomly I can't place or target a gameobject (they are 100% clones of other ones):
The only thing to do is debug
in what way specifically?
In the normal ways. Log important values and if conditions and see what's going on
Alright
Debug.Log, and/or the debugger in your IDE
I'm experimenting with procedural animation, and I am trying to make this little worm guy, but I am having some trouble. Here is my script: https://hastebin.com/share/gesiqonufe.csharp. I think whats happening is the segments are folding in on themselves, is there a way I can prevent them from folding in on themselves, without making them collide with eachother?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Oh, my bad
Here is a video of the issue: https://streamable.com/kcrv6h
I recently learned that not unsubscribing to an event causes the subscribed object to not be garbage collected properly after its deletion.
I know this is bad practice since it doesn't free up unnecessary memory but my question is does it cause any unexpected behaviour in/after the deletion of the object? As far as I understand the reference to the subscribed delegate still exists and it gets called but it does nothing. I tested this scenario and nothing crashed.
what does <> in class declaration mean ? e.g. public class Grid<TGridObject> { { }
is it related to generics?
Yes TGridObject is the generic type parameter of Grid class. TGridObject isn't an actual type but when you create a Grid you will have to specify what its type parameter is and every instance of TGridObject in the Grid class will be replaced by the runtime type.
thanks!
that's a bear by the way
If i'm running a script from the event trigger thats on another object how can I get the object that is calling the script?
By event trigger did you just mean event? If that is the case, you can have the object as a parameter and feed in ‘this’ (if you wanted the invokers class) or ‘gameObject’ (if you wanted the invokers GameObject) whenever you invoke it
Is anyone good with decoding error messages? Im not sure what this means or why I cant use this. The docs say that I can use Network Objects but its obviously still returning an error
(2nd image is a screenshot of the docs)
And for more info, the _nobPrefab is a network object
[SerializeField] private NetworkObject _nobPrefab;
This is a very simple error in plain english. Just look at the method. It takes two parameters. You passed one.
It wants a bool for the second parameter. It is called asServer
oh I see it now
I didnt know that it shows you what it needs
thats cool to know
thanks!
whats the difference with transform.Rotate and Transform.Rotate
lowercase transform isn’t a class. transform is a parameter inherited via monobehavoir
It is just different target
oh okay, thank you
First one is an instance method. The second one is a static method.
That being said, Transform doesn't have a static Rotate method, so I'm not sure where you're seeing that.
I’m not sure what that means, I just got an error and changing Transform.Rotate with transform.Rotate fixed it so I was wondering
how do I start making things without tutorials, I’ve been trying but I just don’t know how to start I know nothing
You had a typo then. Transform is a recognizable name though, since that’s the type (class) of the transform property
oh okay
thank you, I appreciate you for helping me
Does tweaking variables in the editor work because of reflection + serliazation? More specifically for the private variables I suppose
pretty sure it does, also anything string based is gonna be reflection
i dont think theres really another way to get the list of fields that a class has
Hi. When overriding a void, is it normal that even when using the base void, and in the base I do return, it still does what is in the override? Like for example, if I have the following:
protected virtual void FixedUpdate()
{
if (!IsReleased || (ReplayManager.inst!=null&&ReplayManager.inst.ReplayPlaying))//this returns true, so it should do the return
return;
}
protected override void FixedUpdate()
{
base.FixedUpdate();
//some more code here
}
And it is still running the part of "//some more code here", even tho it had a return in the base
It is a function or method, not a "void". A lot of the terms you're saying make no sense
You're calling the base fixed update, so itll run and return back to your method call of it. Return is not some magic which stops execution of everything
Oh okay, I thought return stopped like that method from continuing executing. My bad. I'll have to find something else then
thanks
this looks like the base class isnt even doing anything in that method. If you just have that logic in the derived class itll be easier for deciding what logic should happen next
that wasn't the full code, it was just the part that was causing some problems, but yeah, otherwise it wouldn't make much sense😅
could anyone help me with this?
Why without tutorials? You should be googling for guides or what others have done when making a system that you're not sure of.
And simply you just need more experience coding
i thought tutorials wouldn’t get me anywhere but I’ll take ur advice
thank you very much
In all subjects, if you're blindly copy pasting then it wont teach you anything. You need to see what others do and experiment around
I’ve been trying to understand all the code but I’ll start experiment with it as well
Test yourself: can you rebuild it without looking at the reference a week later. If you can, you have learned it, if not you didn’t learn enough. If you recreate it by memorizing, you likely also haven’t learned it yet.
The idea generally is that if you understand something once, it will be impossible to forget. If you forget you have not understood it.
most of the time it’s the math I dont get, I’ll keep trying though
Well, understanding math takes a lot of effort. Very few make that effort outside university.
I’ll try my best thank u for your advice
Hey guys
I'm trying to create a 2D Wall that starts off invisible but fades in to become opaque as the Player gets closer in its Trigger
Does anyone know a good tutorial for it? My code works but the problem is that when the Player is inside the Trigger the Wall keeps fading in from 0 to 1 alpha every time the Player presses an input
at a guess you woould want a raycast and a Lerp in OnTriggerStay2D
Thank you, I actually just figured it out by accident
actually you dont even need the raycast, the Collider info can give you a distance
How so?
Vector3.Distance from the player to the collider and feed that into the Lerp
I didn't use a Raycast or Lerp, just a Coroutine that does this
wallSprite.color = new Color(wallSprite.color.r, wallSprite.color.g, wallSprite.color.b, wallSprite.color.a + Time.deltaTime * fadeInSpeed);
Lerp and MoveTowards were giving me funky results
that will not work for 'less transparent the closer the player gets'
You're right, but I spent an hour+ on that problem so I'm happy this works lmao 😅
I'll try one last time with your method
Oh wait, Vector2.Distance, I did try that
yes, and you need to convert that into a value between 0 and 1 for the Lerp
private void OnTriggerStay2D(Collider2D collision)
{
if (!playerInTrigger) { return; }
// If the Player stays in the Trigger
if (collision.gameObject.CompareTag("Player"))
{
// Calculate the distance between the Player and the Wall
float distance = Vector2.Distance(collision.transform.position, transform.GetChild(0).position);
// Calculate the alpha of the Sprite based on distance and maxDistance
float alpha = Mathf.Clamp01(1 - distance / maxDistance);
// Update the wall's color with new alpha value
// wallSprite.color = new Color(wallSprite.color.r, wallSprite.color.g, wallSprite.color.b, Mathf.Lerp(wallSprite.color.a, alpha, Time.deltaTime * 5f));
wallSprite.color = new Color(wallSprite.color.r, wallSprite.color.g, wallSprite.color.b, alpha);
}
}```
Hmm, maybe I don't understand what you mean but when I used the above method, the input problem still existed and the fading out was instant while only the fading in was smooth
even though they use the same logic and I even tried a slower fading out than in speed
It's like the Wall reevaluates every time I press an input when I'm inside the trigger and starts fading in from 0 alpha again
look at it this way
onTrigger enter you have a player position and a collider position. this gives you a distance which is your total distance.
in on trigger stay you calculate the current distance between the player and the collider and then use that to calculate a factor of the total distance, 1 - that is your Lerp t
private void OnTriggerStay2D(Collider2D collision)
{
if (!playerInTrigger) { return; }
// If the Player stays in the Trigger
if (collision.gameObject.CompareTag("Player"))
{
// Calculate the current distance between Player and Wall
float currentDistance = Vector2.Distance(collision.transform.position, transform.GetChild(0).position);
// Calculate the lerp factor based on the current distance
float lerpFactor = 1 - Mathf.Clamp01(currentDistance / maxDistance); // maxDistance is a private var
// Apply the calculated alpha
wallSprite.color = new Color(wallSprite.color.r, wallSprite.color.g, wallSprite.color.b, lerpFactor);
}
}```
oops
not sure why you need the Clamp currentDistance / maxDistance should never be > 1
one problem is this
wallSprite.color = new Color(wallSprite.color.r, wallSprite.color.g, wallSprite.color.b, lerpFactor);
you should have a startColour and an endColour not reuse wallSprite.color all the time
The input reevaluation still exists :/
but there is nothing there that deals with input so how?
I don't know, maybe it's because OnTriggerStay runs every frame or something, I'm not sure
that has nothing to do with input
Do you see any problem in the way I'm calling my coroutines
private void OnTriggerExit2D(Collider2D collision)
{
// If the Player exits the Trigger
if (collision.gameObject.CompareTag("Player"))
{
playerInTrigger = false;
// Stop any ongoing fade coroutine
if (fadeCoroutine != null)
StopCoroutine(fadeCoroutine);
// Start fading out the wall
wallSprite.color = new Color(wallSprite.color.r, wallSprite.color.g, wallSprite.color.b, 1f); // hard coding full opacity here because of funky behavior
fadeCoroutine = StartCoroutine(FadeOut());
}
private IEnumerator FadeOut()
{
// Gradually decrease the alpha value to fade out the wall
while (wallSprite.color.a > 0f || (playerInTrigger == false))
{
// wallSprite.color = new Color(wallSprite.color.r, wallSprite.color.g, wallSprite.color.b, Mathf.MoveTowards(wallSprite.color.a, 0f, Time.deltaTime * fadeOutSpeed)); // Faster fade out
wallSprite.color = new Color(wallSprite.color.r, wallSprite.color.g, wallSprite.color.b, wallSprite.color.a - Time.deltaTime * fadeOutSpeed); // Faster fade out
yield return null; // Wait for the next frame
}
}
}```
apart from the facxt that it should be using the Lerp factor last calculated in Stay to go back to zero and the same incorrect usage of wallSprite.color, no
Sorry I forgot to update that, but I'm not sure it will solve the input issue
but this has absolutely nothing to do with input so I don't see where that can come from
Yeah, it's strange, it doesn't happen when I do the non-distance dependent method. I've spent 2 hours on this, better to move on 😅 Thank you very much for your help
the distance dependent opacity would be a bit fancy anyway
#copium
It's really not that difficult and is a quite common mechanic
yeah, but I bet you just used blueprints rather than writing the bare C++
No lol, it was C++ but I admit I followed a tutorial
is there anyway for an animator event to call a function in a script not attached to the same object
pretty sure the answer to that is "no" but you can always have the animator event invoke some method that invokes another event that your other objects can subscribe to
Guys I am trying to play a video via Video Player component on a 2d canvas, I am using a basic lit URP mesh rendered material (color: white). As soon as I press the button to display the video, it still remains white. I can hear the voice but nothing show up and am getting this debug.log "Unexpected timestamp values detected. This can occur in H.264 videos not encoded with the baseline profile. Timestamps will be skewed to correct the playback for C:/Unity/OKI! Friends/Assets/Voicecall Video/Demo_Video_NEW.mp4"
I have not transcoded the video in unity still as the codec is already H264
For unity localization package, how can I get the percentage formatter {x:0%} to work correctly? or do I have to implement my own custom formatter for this?
Help me:
I did...something and now when i want to select and move objects i can hover over all vertices instad of having the object selected.
- What is that called?
- How can i disable that?
- if i hold ctrl the transform-gizmo is set to the pivot of the object, ...i think i accidentally activated something
Look at the top of your scene view
Probably ProBuilder vertex mode
Switch back to Object mode
(this screenshot is too zoomed in/cropped)
Also this isn't a code question
What would be the correct way to make a Texture, used in the custom Editor's GUILayout.Toggle's GUIContent, smaller, as it is displayed with its original size? Does copying the Texture and changing its size sound fine? If so, what would be the most suitable way to do this?
Doesn't it use whatever Rect you pass it?
No, it doesn't
Pretty sure it does.....
hi! i'm trying to build asset bundles on apple arm, i'm using this:
BuildPipeline.BuildAssetBundles(assetBundleDirectory, BuildAssetBundleOptions.None, BuildTarget.StandaloneOSX);
but i think StandaloneOSX only supports intel
is there anyway to get arm working?
I see, that's GUI.Toggle. It's different from GUILayout's and I am still not able to change the Texture's size
I wonder if once unity moves to coreclr, do we still have to deal with assembly reference files and unity overwriting every cs project files?
speaking about Unity's Localization tool... is there a way to know whether a LocalizedString that contains other LocalizedStrings as values for its variables is ready?
I came across this problem yesterday, in which my localized string would just print an empty string instead of the localized string value it contained... I tried running RefreshString() over and over, but it would return false every single time... I had to subscribe to the StringChange event, but it was kind of a bummer to do lol... I would have preferred to have a coroutine to wait until it is ready and then set the value (I know it wouldn't update if I change the language, but I can handle that)
Oh, i got the wrong channel. Oopsie. It was not ProBuilder Vertex mode, it's in object mode.
Edit: And it's gone after restart. Well now i will never get to know what that feature is. ^^
Anyone that knows a bit about serialization available to help a bit?
I am setting up a save/load system in my game and having some doubts about the reliability. My game data is stored in a single, "master" C# class (not monobehaviour nor scritableobject) named GameState. I can serialize it all without any issues using JsonUtility, and it SEEMS to be working alright for now.
For other normal serializable classes, all the relevant data is there and it seems to be OK.
Now, when I get to ScriptableObjects, things are looking a bit iffy. I know already I cannot serialize the SOs themselves, this is not what I am trying to do. What I am trying to do is just store the references to them in my save file so when I load the game, they get put back in their positions. This SEEMS to be working for now, but the save file has "Instance_ID"s for each, and those are NOT permanent, right?
I looked around a bit and only found some really old posts talking about that. Do any of you know if any recent unity update fixed that behavior somehow or if this is still an issue?
What are my options here? Dropping SOs and using normal classes for all serializable data? Or setting a dictionary so jsonutility saves and loads them with "other names" in order to make it work properly? The second approach would be a bit complicated because my SOs are quite spread around in my data tree.
I was typing the question! Hahahaha
Should have put it all together, though, sorry for that.
No that's not going to work
you need to have your serialized data reference the SO asset in a different way
For example by name to use with Resources.Load
or with an Addressables Asset
or with some custom identifier you make that you know how to resolve to an actual reference
Yeah, that's what I thought. Dang it. If JsonUtility just got the GUIDs of the assets it would be so much simpler T.T
I see
or, yes, drop SOs in your serialized data entirely
Got it. Either drop SOs or transform their references into something else and manage a way to put them in their slots when loading.
I will look into the addressables, maybe. Because I've read "resource.load" can be a bit bad performance-wise?
I thought about just creating a dictionary of all my SOs x Unique identifier but I have no clue of how to make the game read that and find the assets (beginner here). The closest to that would be Resources.Load, correct?
Yeah the dictionary idea is good
yeah you could do that. basically something like this (contrived example):
[Serializable]
public class ItemData {
[SerializeField] private string itemId;
public ItemSO GetItemSO() {
return ItemDictionaryManager.Instance.GetItem(itemId);
}
}```
An Array may be better, if the SO's inject themselves into a fixed index of the array and the reading classes read from that index it's just a case of storing an int on both sides
This seems interesting. I will try implementing something similar.
Maybe a List would be better so I can scale my data up while I produce new objects and whatnot, no? That is, if I want to keep it simpler like that.
Or maybe set another SO that just has lists for each type of SO in my game and somehow make this interact with the serialization/deserialization.
the problerm with a list or array and depending on index is that you can't ever rearrange that list or array or remove things from it
no, because you would have to ensure the correct sequencing adding to the list, with an array you dont have that problem
So then the SOs will be organized such as "Armor[1]", "Character[5]" and so on, always being unique.
True
even when you update the game
But an array has a fixed size, no?
yes, but you wont be creating new so's at runtime will you
Not at all
so fixed size is not a problem
Hmm... I can make it generate for every SO of a type within the contents folder and it will have the exact size always, right? However... What if I ever remove an object like Praetor mentioned? The other slots won't "move" but that one will be left empty correct? Would a dictionary be better with that? Or just setting an UID inside the SO itself and making the game read it and look for that when populating the slots?
tbf you could implement the Dictionary approach for ease of development and switch to an array for production. The change would be trivial
That makes sense. While I am changing stuff keep it all as a dictionary to avoid messing up and then when stuff is more set in stone, change to an array.
But how exactly do I integrate any of those approaches with the serialization/deserialization process? The serialization is actually straightforward, my issue is with the deserialization.
How can I make the engine populate the SO slots with the original SOs after it reads those unique identifiers?
you just need to store the itemid on both sides
Hmm... I don't quite follow. Which sides you mean?
well on the so itself and the classes using the SO's
Just use a dictionary, no reason for an array
Then you have code in the OnEnable of the SO so it injects itself into the Dictionary
Use a human readable ID rather than an index, you'll save yourself so many headaches
Yeah I think a dictionary is simpler for me especially since I am kind of a beginner still. But if performance is worse or something, I don't mind learning.
The performance difference is miniscule
Dictionary is more complex to use, objectively
An array is just about the most simple collection there is
Oh okay! Now THIS is interesting. Just have all SOs have an OnEnable to autoinject wherever they find "themselves"
yep
Love this approach. Will make it really uniform and straightforward (useful so I don't get swamped in complicated logic lmao
Yes it is! But for readability it is a bit more complicated! Because "LongSword001" is easier to identify than "Weapon[008]", especially for a beginner like me. Or I think at least hahaha
your dictionary can be static or attached to a singleton just to make life easier still
Most importantly, your dictionary doesn't depend on some abstract order
Yeah, the methods I was trying to come up with would put those "onenables" on every class that had SOs, that is why I was considering just dropping SOs altogether lmao
And actually, base C# classes don't even have onEnable.
So it wouldn't even work. But putting OnEnable methods on all SOs that go into serializable classes is WAY easier and uniformizable. You saved my life there @knotty sun! Thank you VERY much!
If your weapon data is just represented on a ScriptableObject, I wouldn't necessarily do that approach...I would use POCOs and serialize them to a file to be loaded at runtime
Base c# classes don't really have anything of course
They have this:
https://learn.microsoft.com/en-us/dotnet/api/system.object?view=net-8.0
Oh? What is a POCO exactly?
What you called a base c# class.
Same thing
Oh! You mean using base C# classes, right? Got it. Yeah I thought about that as well, but having the ease of creating new weapons as separate assets and handling them in the inspector and having the data preloaded into the game on starting is so useful.
But yeah, it is also an option, of course.
It's just that being a newbie in unity, the more "visual" approach of the SOs really caught me. But if setting them up becomes a nightmare I can just keep serialized stuff away from them and use them only for permanent stuff.
Yeah, it's probably more work than it's worth for you, and the overhead from the ScriptableObjects is negligible in the grand scheme of things
And the solution Steve offered should work like a charm too! I will try it out now.
Then again... OnEnable is called when an object is enabled, right? SOs get enabled when the game loads so would it actually work like that?
there is even another way of doing this.
say you have a serializable class
mySOs { public int key; public ScriptableObject so; }
and a Mono class
MySOs : Monobehaviour {
static Dictionary<int,ScriptableObject> soDict;
mySOs[] mysos;
}
then you can just store all your so references on an empty gameobject
and build the soDict as part of the Deserialization operation
I see... I will explore those and report back when I manage to implement. It would be so good if JsonUtility just used GUID instead of Instance_IDs though... lmao
even if it did it would do you no good, there is no way to get from a GUID to an asset at runtime, only in the editor
Oh, dang. Yeah, so nevermind ahahaha
I am trying to implement the dictionary in a way that it actually "works" during the serialization/deserialization so the class it returns is just right from the get go to replace the "old" one.
If this works the problem is solved. If not, I will try the other approaches.
Hi! I'm trying to lerp an angle from (for example): 315 to 45. I want it to not do a full 180 around to get to 45 but it does that. What's the best way to achieve that? https://gyazo.com/f87b411c34a0891d810bada51e38c924
This is my script for that:
float angle = Mathf.Atan2(target.transform.position.x - transform.position.x, target.transform.position.z - transform.position.z) * Mathf.Rad2Deg;
if (angle < 0)
angle += 360;
transform.eulerAngles = new Vector3(transform.eulerAngles.x, Mathf.Lerp(transform.eulerAngles.y, angle, lookLerp), transform.eulerAngles.z);
^ If i dont do the angle < 0 statement it spins around in circles since its a negative angle and kinda fks up so if you know a solution to that too thatd be nice
Serializing classes with Scriptable Object references
-
UID Dictionary: Set a dictionary to store all SOs and their respective UIDs. This will be populated on Awake of the GameManager object by a populating method that fetches all SOs currently referenced in the game for use during saving and loading the game.
-
Saving: Call the SaveGame() method in which a copy of the current GameState is instantiated and processed by replacing all SOs by their UIDs from the dictionary. With that done, run the JsonUtility to serialize.
-
Gameplay: You can play the game as normal, since the original GameState has not been modified.
-
Loading: Call the LoadGame() method to deserialize with JsonUtility as usual, then substitute the UIDs everywhere in the GameState with their corresponding SOs (SO subtypes are kept). Finally, replace the current GameState with its processed version.
And done, the SO references will be kept in a more secure way instead of using Instance IDs.
Thanks a ton to everyone that helped! ❤️
use Mathf.LerpAngle instead of Mathf.Lerp
What's the use case here? Looks like you're trying to just do a Look At
Does anyone know how to script bullet shell and mag removal system. Also I am working on a bullet trajectory calculator and in it the physical properties get calculated and saved in a file. I want to know how to access and write files in unity
look at the System.IO namespace, particularly the File and Path classes
Neither.
Rust is pretty great from a performance perspective for what it has
I can't speak for EFT
Are they even bad ? For what they offer at least.
But regardless, optimization is complicated
It has nothing to do with poor programming or Unity, it's just hard full stop.
For you ?
I don't remember having many issues with EFT, might be your specs
Everyone that complains*
If it was barely playable then no one would play it
Negative voices are always the loudest
Classic Survivor bias
Check your thermal procs and bottlenecks
So, it runs.
Do you have a programming, Unity specific question? This channel/server isn't the place to ask questions about solving problemns in games you did not make
What is the issue to give better performance for future or better specs
Go on Reddit, if you want to make a hate thread about things you do not know.
Regardless we can't know what's wrong with rust/eft as we don't have the source 😛
It's definitely not Unity at least
No it's just off-topic for this server
What question ?
You didnt ask anything unity related
Who took what personally huh
😂
They're not wrong, though, this isn't the place to complain about built Unity games
Nobody can answer your question here, as nobody here is the developer of the games you're having issues with.
So, the answer to the question is : you can't know. Only developers will have access to the profiling tools
This is purely a development server for people using Unity to make their own games. Any questions/issues you have with existing games isn't suited for this server.
You may want to ask them directly in their community discords, if they have them.
See ya
That was an expert level troll
Inb4 they go to whatever community they want to annoy and say how "I got them good!"
Well im guessing unity wont be their engine to learn anymore
Until after they fail in unreal at least
!kick 431519822203977739 Seeing that you couldn't help but return, I'll help you out: no need to return if you're not here for Unity development questions/discussions.
mynde was kicked.
!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.
Goal: Animation plays when LoadingScreenWillDeactivate is invoked from LSM
Obstacle: LoadingScreenWillDeactivate (L33) seems not to be invoked, but @L31 - @L34 do execute. I'm assuming it's not being invoked because in AC @L15-@L16 do not execute. Placing a breakpoint on L33 has no result, it does not break.
AC (Animation controller)
https://hatebin.com/kojnlgbkfc
LSM (Loading Screen Manager)
https://hatebin.com/oqtcqjvlda
I think the most likely issue is the Destroy call, but the call is delayed and shouldn't stop the delegate invocation anyway
edit: removing the destroy call does nothing. the loading screen is not destroyed and the animation still does not play
even then i'd expect the invocation to succeed but to get a "this object is destroyed" error on the animator
There are no exceptions
animator is not null and animator does have bool 'IsDone'
oh wait i think i figured it out? i think my service getter wants me to use ILoadingManager instead of LoadingManager
nope
its returning the service so it should be subscribing to the event fine..?
maybe interfaces dont like events..? i don't understand
Event not being invoked
Setting the rotation with t.eulerAngles = someVector3 causes the object to sometimes flip 90° on a direction that shouldn't change at all.
What should I use instead? I tried t.rotation = Quaternion.EulerRotation() but that seems to be deprecated.
isnt it just .Euler now
Hi all, I just wanted to know if this code is OK? https://pastebin.com/DY7setf3
(as in, no memory leaks or weird behavior)
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
The way to find out is to test it
As for memory leaks - use the memory profiler
bruh ghost ping
fair enough, just not sure about the behavior of dynamically allocated resources (new Texture2D and Sprite.Create)
I am supposed to destroy them manually?
Does anyone know how to pass a reference to a MonoBehavior method to a static function so that I can call a coroutine from within it?
How do I store the changes made to a scene during runtime into the scene file itself?
i am very confused by transform.TransformDirection
if my transform's rotation euler angle is 0,90,0 and i do TransformDirection on an euler angle of 0,270,0 the output is still 0,270,0
there's not an easy way to do that
rephrase?
to a monobehaviour to a static function is confusing
Sorry it turned my brain to mush
Basically I need to call a coroutine from within a static function, but you can't do that normally because it needs some kind of reference to an object that's under MonoBehavior
idk how to do that in code
well I've tried a few ways
Surely it's not impossibly hard. I'm just talking about having a scene which stays consistent between playsessions. Many, MANY games have that
Which monobehaviour do you want to run the coroutine?
Yes its called a save system and serialization
Cool. How do I do that
it can be the same class that the static function is a part of, doesn't really matter
Which instance
I guess the script instance itself
bump
Player prefs (not recommended), JSON serialization, Binary Formatting (not recommended)
What's wrong with binary formatting?
As long as you arent using BinaryFormatter specifically, it's fine. The only downside (or upside if you dont want users editing it) being it's not human readable
Well, this script instance only exists on just one object, so I tried to pass it through with this but I doubt the reference stays consistent
What have you done in code to let it know that it only exists on one object?
That is a good question
well binaryformatter specifically is insecure, its inflexible (files break when the structure of the code are changed), and its not human readable (harder to debug)
I understand the latter 2 but how is it insecure? That's the first I'm hearing that
Just genuinely curious!
BinaryFormatter has a well known RCE
Microsoft itself heavily discourages using it if you can
There are alternatives, which are listed in the same page. Writing binary itself is not an issue
Right, but binaryformatter is the thing most beginners hop to (besides player prefs)
And the other two reasons still apply
I think it's because Unity literally uses it as an example for serializing in some of their tutorials
that's very questionable
The general process of using a formatter to serialize and deserialize data are pretty transferrable
Just don't use this specific formatter
Well it does work
I'm aware, just didn't know this specifically about BinaryFormatter
Could be a very old tutorial before the risks were known
I also used to use bf until I swapped to easy save which uses json
public static void PlayTitle(MonoBehavior instance)
{
if (!titlePanel.activeSelf)
{
titlePanel.SetActive(true);
StartCoroutine(PlayTitleEnd(instance = this));
}
}```
Bump
So, question:
Why is this static
it exists on an object that arbitrarily is registered and sometimes destroyed conditionally
so I had to do that to make the references consistent
Service locator?
But this specific function can only be run when one does exist
So there's no reason for this function to be on the class instead of an instance
You probably want a singleton
Huh, okay that'll take me a bit to wrap my head around
Idk
The point of this is so that I can disable a fade-in gameobject so that it doesn't overlay over the other UI elements** **
my solution to this in other cases has been a coroutine to disable the object once the animation finishes, and I know there's more than one way to solve this
however as you know it's in a static function in the controller class
or an AnimationCurve, if you want a little more control
didnt know abt this, thats what i wanted ty
Why am I never getting this done the right way regarding Layers.
if (collision.gameObject.layer == projectileData.layerDetection)
Doesn't work properly how am I supposed to do the if line?
- a gameobject's layer is not a layermask, those will not be equal to each other
- why are you trying to compare the layer in the first place?
I just want the projectile to only react to objects that have the Player layer.
How am I gonna do that then? When I just type in the number it works, but I want to be able to set it through the inspector and not static
I just want the projectile to only react to objects that have the Player layer.
then just filter the collisions in the layer matrix rather than comparing the layers
https://docs.unity3d.com/Manual/LayerBasedCollision.html
A layermask is kind of like a list of layers. So you cannot compare them directly
Yeah I see its using bits, thanks for your answers I will have a look
i am confused by transform.TransformDirection
if my transform's rotation euler angle is 0,90,0 and i do TransformDirection on an euler angle of 0,270,0 the output is still 0,270,0
it should be 0,0,0 shoudl it not?
Your euler angles are not a direction, they are a rotation in values we can understand. The vector you have it is essentially just a really scaled up Vector3.Up
In which case both the transform up and vector3.up align
No it does not need to be. I am saying that your vector is not a direction and you've given it a vector that's just pointing up
The object has no rotation on its X or Z. Its local up and world space up are the same
Basically, I have a game object rotated 90 degrees about the Y axis and I want to determine what the local rotation of 0,270,0 is in worldspace
The result I need is 0,0,0
Maybe I'm just going about reaching that value incorrectly
If the object has no parent, its local rotation is gonna be the same as the world rotation
i really need help i deleted my oculus folder cus i got compile errors from the all in one sdk meta and now i got 209 compile errors
I have a local object rotated 270 degrees I mean
Yea it's really unclear what you need this for. What's the actual use case? Why do you need this 0,0,0
now when i open unity i only got 5 errors but everything is pink and i cant find the rendering tab to make it not pink
I have a sub position I calculate in this game object that's rotated 90 degrees
The sub position also has a rotation
So like, if the object rotates then I need to apply it's worldspace rotation to the local rotation value when I compute the position and rotation
Basically I want to take 0,90,0 and add 0,270,0 to it
Could you not just use a child gameobject and have this done automatically?
Long story but no, this is all computed data
It shouldn't be difficult, I'm basically just using the transform to convert that local position and rotation to worldspace
But the function I'm using seems to not do what I need
Converting the sub position to worldspace was easy
But this rotation function isn't giving the expected value
I dont really see whatd stop you from still using a child game object and just reading off those numbers. But yea the issue is what I said above. The method you're using is expecting a direction.
Though what's stopping you from just doing what you said above, adding the 2 vectors of your euler angles?
Maybe that's the correct way to do it, I just assumed that function was the right way
If a game object is rotated 0,90,0 and I transform a local angle of 0,270,0 then should it not add 90 to Y?
That function would be more like "I want my object to move forward relative to itself but I wanna specify (0,0,1)"
Honestly I'm not sure what to imagine in this scenario, the use of local and worldspace in a lot of messages dont fully make sense.
If your sub object is supposed to be rotated 90 degrees relative to the game object then yes just add the 2 vectors.
. . . holy shit...
its not exactly code but it is coding related...
i dunno when it started, but all of a sudden I cant edit the middle of a line anymore in visual studio, i can only replace letters from left to right if i want to add something, a bit like command prompt
anyone know how to disable this?
press the insert key
W thanks
So now that all the forum links are broken, is there a way to find those posts on unity discussions? Tried looking up the exact title but couldn't find the post.
gotta wait till the migration goes fully through
it says that the migration is "fully complete" D:
maybe links didn't propagate or update dns yet
aight lets carry on here lol
ive just checked all the pixels , they are correctly mapped
so the only problem will be
- is color32 converted completely empty
- other possible reason that is blocking the setpixel or apply
I meant post it here seems to be code related
I didnt read the whole thing yet
i got adhd lol
You should share more of the info. Like the whole code of setting the texture colors and applying them. As well as how you're confirming that there is an issue.
hold on lemme test one last thing
Hello, I am having trouble with audio in my 2d platformer. I have two scenes with different music playing in them. My Menu Audio Manager should be destroyed when a new scene is loaded but it stays resulting in both sets of music playing at the same time, please help!!
BRUUUUUH
the texture is not correctly mapped simply because the texture pointed to the image was dereferenced
i found out the problem , thx
👍
I have a button that I want to run a method in a script on another object when clicked, problem is that that method takes 4 parameters and button ``onClick()` only allows for methods with at most 1 parameter
anyway to get around that?
don't think if you want to use inspector
Dang I'm making a crafting system and I want it to be as dynamic as possible so i didn't want to hardcode recipes
You could probably wrap it in another method
how so?
using delagate with AddListner
how hard would it be to make recipes loaded from a json file?
I'm trying to remember it rq, I havent used inspector for this in a while
not hard at all
Maybe I should just do that then
yeah imo thats clean and easy to even update remotely
How do I parse a json file in c#?
Read the text in the file, then convert it into a poco
sorry what's a poco?
ohh alright
I did this:
public void CraftRecipe(string recipe)
{
TextAsset json = Resources.Load<TextAsset>("Recipes/" + recipe);
Recipe recipeObject = JsonUtility.FromJson<Recipe>(json.text);
Craft(recipeObject);
}```
is it working ?
Hi, there. I'm attempting to create a first person controller with 6 degrees-of-freedom movement in a zero-gravity environment. I have a camera holder that moves to a specified empty child of the player object with LateUpdate. I am translating the player's rigidbody with AddForce and rotating the rigidbody with MoveRotation with FixedUpdate. (I was initally rotating the player's transform directly with transform.Rotate.)The translation works great, but the rotation causes camera jitter. The jitter is especially noticeable when translating and rotating at the same time.
My understanding is that camera jitter on a rigidbody player controller is very a very common issue for beginners. I've tried following quite a few guides on Youtube, the Unity forums, and Reddit. So far, nothing has worked. Many fixes I'm seeing don't apply to me because of my unique camera set-up and movement system. My intention is for the mouse input + roll keys to rotate the entire player object, so a traditional FP controller setup does not work for me.
Thing's I've tried: The rigidbody's interpolation is turned on and I have tried both settings for it. I have tried changing the camera holder move script to FixedUpdate and regular Update. I have tried making the camera update move and rotate to the rigidbody instead of the player's transform. I have also tried making the camera a direct child of the player object.
All three of my C# classes: https://gdl.space/yokesabive.cs First one handles the rotation inputs and applies rotation to the player's rigidbody. Second one handles translation. Third class is on the camera holder and updates its own position to be that of the player's position. (The main camera is a child of the camera holder.)
Screenshots of my editor setup are attached.
Why not add a constraint to the camera?
Can you please elaborate?
I am unfamiliar with the concept of constraints on a camera beyond a MathF.Clamp on a camera's rotation
Add a constraint component on camera holder and set the target to camera position.
Thanks, I understand now. I was unaware of constraint components. I'm testing it now.
I've now set up the constraint components and it seems to have reduced the amount of camera jitter significantly. There's still way to much for the kind of game I'm making, but now that I know about constraint components I'm going to give another technique a try.
Just use Cinemachine
I have a variable i want to set: inventory.wood but I don't want to write a separate line fo code for each object. Would I be able to pass in a string instead of wood? So something like inventory.(this.blockName)?
or enums
explain please
could also be scriptable object but thats more advanced.
what do you want to do with the string anyway?
i've never used them before lol
I'm trying to access a variable of another script so that I can set another variable to match it
public class Foo : MonoBehaviour
{
[SerializeField] Resource theResource;
}
public enum Resource
{
wood,
stone,
metal,
}```
public void ChangeResource(Resource resource)
{
theResource = resource;
}
private void Hi()
{
ChangeResource(Resource.wood);
}```
I did some research on enums. Is it true that I can only hard code their values?
wdym "to match it"
whats the mechanic here?
this is what I'm trying to do essentially:
private void Start()
{
associatedPrefab = Resources.Load<GameObject>("Prefabs/Building Blocks/" + blockName);
UpdateText(associatedPrefab.GetComponent<BlockAmount>().amount.ToString());
if (GameObject.FindGameObjectWithTag("Inventory"))
{
GameObject inventoryObj = GameObject.FindGameObjectWithTag("Inventory");
switch (blockName)
{
case "Log":
amount = inventory.wood;
break;
}
}
}```
jesus this is already overconvoluted
inventory.wood is an integer
so you're trying to do an inventory count?
I know I shouldv'e used a dictionary but i'm too far along to switch to one
yep
then yes use a dictionary..
I have 2 scenes with 2 different inventory implementations and I need to keep them consistent
what does have to do with dictionary
wat values are you talking about
using a switch for this when you can easily do it in 1 line with dicionary
Yeah that's what i'm saying, a dictionary would be better. I just don't want to use one because i'd have to rewrite a lot of stuff
the way you're doing it now is not good and not very scalable.. rewriting code is part of the work
It shouldn't need to be super scalable, it should work for what I need it to]
You're looking for advice, i've given it, you said yourself you need dictionary. Figure it out idk what to tell ya lol.
It's tempting to "let the future me deal with it" but if you foresee your future self saying "this has gotten so bad that I can no longer continue working with this code and need to refactor it, I should've just done it two months ago and saved a bunch of time during the two months" then you might as well do it now.
good advice, do not intentionally cause your future self pain
what takes a day to fix now could take a week or more to fix in the future
Tech debt rarely shrinks by itself 😄
This missing reference is eating my head, Basically this only comes sometimes, if i add some debug or something in the code and run again its not coming, also in the build its not happening, only in the editor its happening, Is there any fix for this or has any one faced this before? please help.
Error:
MissingReferenceException: The object of type 'UI_References' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.MonoBehaviour.StopCoroutine (UnityEngine.Coroutine routine) (at <2d8783c7af0442318483a199a473c55b>:0)
UI_References.SetLoadingScreen (System.Boolean status, System.String msg) (at Assets/UI_References.cs:111)
LoginManager.Init (System.Boolean isTestUser) (at Assets/LoginManager.cs:102)
GameConfigurationManager.ApplyRemoteSettings (Unity.Services.RemoteConfig.ConfigResponse configResponse) (at Assets/UI Manager/GameConfigurationManager.cs:101)
Unity.Services.RemoteConfig.ConfigManagerImpl.HandleConfigResponse (System.String configType, Unity.Services.RemoteConfig.ConfigResponse configResponse) (at ./Library/PackageCache/com.unity.remote-config-runtime@4.0.2/Runtime/ConfigManagerImpl.cs:553)
Unity.Services.RemoteConfig.ConfigManagerImpl+<>c__DisplayClass46_0.<DoRequest>b__0 (UnityEngine.AsyncOperation op) (at ./Library/PackageCache/com.unity.remote-config-runtime@4.0.2/Runtime/ConfigManagerImpl.cs:542)
UnityEngine.AsyncOperation.InvokeCompletionEvent () (at <2d8783c7af0442318483a199a473c55b>:0)
How do I actually "save" values with ScriptableObject?
I have one that get filled by a [ExecuteInEditor] script, and while I can read it perfectly it get reset to null everytime I load a new scene or restart the editor.
Tried AssetDatabase.SaveAssets, but it's not doing anything so I'm kinda confused on how to do it.
did you SetDirty before Save ?
I didn't even knew that was a thing.
Tested it and it look like that did the trick.
Thanks!
bro my entire project is fucked for some reason uninstalling 1 folder corrupted my project cus when i go in to the project all my plugings are gone it uninstalled all my FUCKING stuff like xr pluging manament and all and it removed all my scripts and for some reason my fucking map has a skinned mesh render now and i cant restore it
Guessing you weren't using version control, in which case this is your lesson to start. Look into using git
i am
Then you'll have to be more specific, probably in a different channel though because this doesnt sound like it's anything code related.
If you have version control then you can simply just go back to an earlier commit where everything was fine or even redownload the project if needed from that commit
bro i dont know how
i got unity version control but i dont know how to go back versions
i dont even got the tab for it
it uninstalled it
I dont use unity vc, have you googled anything related to that? And have you even made commits ever for it
I dont really see how anything you said was XR specific so I dont know. I strongly suggest you look online for how to use or find your unity version control so you can see if you can revert. Though if nothing was ever committed then you dont really have something to revert to
using (var memStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("bundle1"))
{
if (memStream != null)
{
MelonLogger.Msg("memStream is not null");
byte[] byteArray = new byte[memStream.Length];
memStream.Read(byteArray, 0, byteArray.Length);
MelonLogger.Msg($"ByteArray length is: {byteArray.Length}");
assetBundle = AssetBundle.LoadFromMemory(byteArray);
var prefab = assetBundle.LoadAsset("test", Il2CppType.Of<GameObject>()).Cast<GameObject>();
}
else
{
MelonLogger.Msg("memStream is null :(");
}
}
What here could cause prefab to be null?
perhaps you should ask in the community for the game you are modding, or in the mod loader's community
I have, already
okay well this isn't the place to get help with modding, it is against server rules #📖┃code-of-conduct
Alright
Hello. I have again come here and seek answers from the gods of the unity community to help with my problem. my console says after shooting the raycast LineRenderer.Setposition Index Out Of Bound. Any good tricks to fix this?
you need to set the number of positions first
not really, just someone who can be arsed to RTFM
Sometimes when i hit play button in editor, it infinitely stucks on reloading domain. Recently i discovered that is happens only when PC connected to internet. Without internet connection everything is fine 🤷♂️ How to fix it? My current version is 2023.2.5f1 but i tried a lot of different versions so i assume problem is in my project. ChatGPT 🤖 adviced me to figure what of my assets can use internet connection by searching words like "www" "http" and other in project, but i didnt find anything like that 
does anyone know how to make a line renderer thin out over time?
best bet, close project, delete Library folder, open project
yes, use the width curve
oh alr thanks
did it, doesnt helps
you are on a non LTS version of Unity, is there a reason for that?
no
then I would suggest you either move to the latest Unity 6 preview or regress to the latest 2022.3 LTS. If you regress create a new project with the editor version and use asset->export asset->import to migrate your project
i tried a lot of versions, including 2022.3 LTS, unfortunately i had same problem on it
interesting, did you check the editor !logs to see if anything odd was happening?
yes, i checked it, but didnt get what it says, i am bit dumb( but i tried to compare logs with and without internet and didnt see difference
next time it happens, post the log to a paste site and ping me then I'll take a look
can any one help me with this script : using UnityEngine;
public class jumpscarestranger : MonoBehaviour
{
public float maxRaycastDistance = 10f;
public Transform playerCamera;
public LayerMask interactableLayer;
public MonoBehaviour playermove;
public Transform target;
public AudioSource audioSource;
void Update()
{
// Create a ray from the camera's position along its forward direction
Ray ray = new Ray(playerCamera.position, playerCamera.forward);
// Check if the ray hits an object on the specified layer within the max distance
if (Physics.Raycast(ray, out RaycastHit hit, maxRaycastDistance, interactableLayer))
{
audioSource.Play();
playermove.enabled = false;
playerCamera.LookAt(target);
}
}
}
when it look at the interactableLayer it just turn to target without activate the sound
you are starting the audio EVERY frame
also when someone shows you a bot message READ IT
bot msg ?
ohhhhh sry bout that
wow, i needed to make a batch file, haven't made a complicated one in over 20 years and forgot most of it ... microsoft's copilot (chatgpt thing?) basically held my hand through the whole thing, and when i had syntax errors, i pasted the whole code into it and asked how to fix it, and it very accurately fixed my errors as well as explaining what was wrong ... geez
amazing isn't it, DOS has changed very little in 50 years and it still underpins everything we do
Hey guys
I'm trying to create a Laser Trap that tracks the Player's position and rotates accordingly
It does that, but the problem is that
I want it to scale depending on the Objects it hits. So if the Player is under a platform, its Collider and Sprite should shrink so that it's hitting the platform, and then scale up again when the Player is in an open area. I do not know the right way to implement this.
But the tracking and rotating of the Purple Block itself is working correctly.
will you please learn to type in full sentences
I'm GenZ, Sir
So what, the rules of the server still apply to you
.