#archived-code-general
1 messages · Page 116 of 1
Same as storing an anonymous object in a variable, then it's just an object because it will need a type to be stored 😄
right the OP in the first example is not using the same delegate. They subscribed with an anonymous delegate and then stored a second anonymous delegate in a variable
References can be very confusing to understand, but it's used more often than you might realise
oh yeah, it makes perfect sense now that I'm done misreading it :p
if a type has no definition for equality, then you just get reference equality: are they literally the same object
and, thus, in this case, that didn't happen
And sadly there's not much you can compare delegates with
ᵘⁿˡᵉˢˢ ʸᵒᵘ ᵐᵃᵏᵉ ᵃⁿ ᵉˣᵖʳᵉˢˢⁱᵒⁿ ᵒᵘᵗ ᵒᶠ ᵗʰᵉᵐ
If I subcribe like this, Unity raises this error: Argument 2: cannot convert from 'VisualScripting.EventReceiver.OnEventRecivedDelegate' to 'System.Action<string>'... @thin aurora
should work if you just make protected OnEventRecivedDelegate EventRecived; into protected Action<string> EventRecived;
Weird, because it's the same thing
I guess the compiler is not smart enough for it
sadly
So what PraetorBlue mentioned is the best solution
OCD moment - The correct spelling of the word is "received" 😆
You should use the the second solution btw, not the first one
Then you don't even need a seperate delegate declaration
This works. Thank you so much to both of you
what is the best way to check for an item besides tags?
To check if an item is an apple or a banana without using a tag for each fruit, for example
maybe a script with public enum type
checking what type of script is attached to the object or checking the value of an Enum variable declared in a script attached to the object.
how can i resize the grey box on the outside? or at least move the pivot point since its messing up my raycasts
for sprites you can change the pivot point in the sprite editor or in the inspector directly
if you are using a SpriteRenderer, the size of the grey box is the size of your sprite => it shows the transparent part of your png file
hey, what s the best way to do a player movement like this
rb.velocity = new Vector3(movement.x* speed, rb.velocity.y, movement.z* speed);
but make that it can bounce on bounciness Collider?
I think what you want is to add your input velocity to the objects current velocity (use Mathf.Min with the normalized value to set a max speed)
ty
I'm trying to call a function on Click on a ui image, I have a public Action triggered on click via a EventTrigger.
My problem is that I register to the event in a for loop which loops through my clickable images (0-3) but when I click the value passed to my function is 4
private void SetupRemoteButtons()
{
ScientistRemoteButton[] remoteButtons = remote.data.GetButtons();
//buttonUIs = new ScientistRemoteButtonUI[remoteButtons.Length];
for (int i = 0; i < remoteButtons.Length; i++)
{
//buttonUIs[i] = Instantiate(buttonPrefab, buttonsParent);
buttonUIs[i].Setup(remoteButtons[i]);
buttonUIs[i].OnButtonClicked += () => UseRemoteButton(i);
}
}
private void UseRemoteButton(int buttonIndex)
{
if (FightScenesTimeManagement.IsPaused || FightSceneState.FightState != FightState.Fight) return;
if (buttonIndex >= buttonUIs.Length || !buttonUIs[buttonIndex].IsSet) return;
buttonUIs[buttonIndex].UseButton(allies.units);
}
Changing the array size still sends the last value of i in this for loop (array length)
heu... rb.velocity = Vector3.Lerp(rb.velocity, new Vector3(movement.x * speed, rb.velocity.y, movement.z * speed), 0.5f);
but it s not what i want
ah i add my input velocity and then i Clamp i g
yes exactly
ok thks i ll try it
ayo does anyone know a fix for this, im new to unity and this seems like something pretty basic that should have an easy fix for it. I am essentially trying to create mutliple hitboxes for a unity game object and have one hitbox for physics and another acting as a hurt box that is larger and in a different shape that the original physics hitbox. I just cant find any way to declare another hitbox that doesnt mess up the other hitbox and I think that I am just missing some fundamental thing bc it seems like there should definitely be something basic for this
use layer
attach the collider(s) in child gameObject and assign it different layer
Does anyone know how I would get the asset name from a Serialized Property?
I'm trying to get "New file" in a string. If I do SerilaziableObject.FindProerty("NodeGraph"), then serializedProperty.name is NodeGraph...
serializedProperty.objectReferenceValue.name
Thank you
I think that answers my second question too...
Hello guys, I would like to use Rider as a code editor but I have an issue:
My game is divided in 3 parts, a game "engine", a server, and the graphical part (with unity). The server and the game engine are in pure C# without unity. Both the server and unity part both need the game engine to function.
So I wanted to create a rider solution that contains the 3 projects, with the correct dependencies between them. The problem is that when I try to add projects to the generated .sln file, they disappear after some time, probably because this file is 100% handled by unity and shouldn't be modified.
What would be the best way to do that?
As you surmised, Unity will always demand it controls the project/solution files for the unity piece
your best bet is to make a shared library project and share it with unity either as an embedded package https://docs.unity3d.com/Manual/upm-embed.html or a nuget package with something like https://github.com/GlitchEnzo/NuGetForUnity
Best way is probably ask yourself why you're using unity for graphics only, why not just implement the game and server in unity.
Is there a reason why you want it split up into 3 projects?
The server could be split I guess
I'd also say if you want to split it up like this C# probably isn't the best language to make the game server in. Why not C++ or Rust or something
Only the server could reliably be split up if it is just used to relay information. And even then if you try to add verification for anything, itll just be harder not having UnityEngine on top of it
I question if this is even a game
The game engine is basic in a sense that it doesn't have any physics, imagine it like a game a chess, it's like the "rules" of the game so I don't see any reason to use unity
Exactly what I'm saying?
I mean even then... unity doesnt force u to use physics
I think I saw something about stripping physics out if u dont need it entirely
I run the server without unity, and the server needs my game engine to run, so that's why my game engine must not be with unity
and that's why I dont write the engine in another language because I still want the graphics part to be in unity, and I want to use the same game engine library in the graphics part than in the server
That's not a reason for why your game engine has to be outside unity.. what does unity even affect in that case?
Didnt u say its in c#?
Unity is not "another language"
no I mean the server runs without unity, so I kinda don't want it to use a library that requires unity
but are you saying it's a bad idea to have my server run outside of unity?
Anyway I've given my advice for this configuration, best of luck: #archived-code-general message
It just doesnt make sense as to what you're doing. Im not entirely sure if you know what you're doing since you called it "another language" but said all are in c# already.
I mean it's possible you can get it to work, but if u dont know what's happening then you're gonna have a really tough time with this
A server is kinda vague, it can be used to just store information or actually connect players in a fps. If it's just to store information, then yea it doesnt really matter where you put it. If you're trying to connect players, theres gonna be challenges syncing UI without UnityEngine
no no lol I talked about another language because @leaden ice said it's probably better to create a game server in C++/Rust. My server runs in C# because it's using the same game engine than the unity game
Ah my misunderstanding
basically it's a 1v1 game with a server handling everything
I kinda thought having the server without unityengine would make things easier, but maybe I'm wrong on that
i don't see how that could possibly make it easier
Well if you arent gonna sync any of the graphics, maybe it will work just the same..
Im kinda confused how you even have a game engine and server but no graphics at all, like how did this code come to be?
well the server only needs to synchronise the actions every player do, and in my game the actions are pretty simple, move a unit here, place a building there...
I only need graphics for the player, so I don't push anything graphic to the server
So the server can be a plain old C# app, it has types that will pretty much map Unity types 1:1, like the stuff in System.Numerics
Yeah you'll have to separate it as Unity has full control over the whole solution
If you need to put both in version control, then pull the git root one folder up, and leave the Unity gitignore at the root of the unity project (now one folder down compared to the git root)
ah that's a good idea, I'll try that thank you
Really bad idea to divide your project by Server/Client. It will be a nightmare to synchronize all the data between both. You will not be able to use ScriptableObject by example.
how do i disable an input
It works well, only issue is that when I try to open a file from unity, it opens the .sln file in the unity folder, and not the one on the root, do you know if it's possible to change that?
No because there will be two separate solution files *.sln, one for Unity to fully handle (your game), and another for your C# app (the server)
Pulling the git folder up just makes it so both solutions are included in the repository
There shouldn't be any sln file at the git root though
.git/
game/
game.sln
server/
server.sln
and what if I wanted to do something like
.git/
main.sln
game/
game.csproj
game.sln
server/
server.csproj
and add to main.sln all csproj I need?
is this possible?
No, you can't make a solution include another solution that's nested
even if I just include the csproj?
Yes because that will break Unity. Not sure if you can have a "shared project" between two solutions either, and even if you can, the Unity one requires references to Unity libs, including it into another solution may or may not cause serious referencing issues
I see nothing wrong with keeping two separate solutions within two separate folders
I would just be pretty convenient to have everything in one solution so I can see where everything is used, but I guess I'm too greedy
thanks for your help anyway
well its reasonable to split the game server in another project, maybe you want to dockerize it or something
..if you want something to compile in a different assembly you can use assembly definitions.. is this what you're trying to do?
i dont really understand what your goal is. if you want to split your business logic to make it look something like clean architecture, of course you could.. what is your goal?
I don't know what assembly definitions is, but maybe it's what I'm looking for.
My goal is to compile into 2 things, one server and one unity game, and I placed everything I need in both in a library that I call game engine, and now I'm just trying to find a clean dev environment to develop that
Assembly definitions is the Unity way of "creating a project in the solution". Outside of Unity you'd do that in VS, which allows you to control what references what.
But since Unity takes up a full solution by itself, you use asmdefs which are folder-based
Is it bad practice to do this?
public static AssetRegistry Instance;
In Java it's bad as it should be replaced with Dependency Injection
But i'm not completely sure about Unity/C#
Outside of Unity you'd most likely use DI, like for ASP.NET websites where the DI framework is pre-installed. For Unity you'd have to install one
But having those things are pretty common yep, singleton pattern
if you're like me and you absolutely hate the idea of any class accessing the value and modifying them in an unexpected manner, Zenject is a way to go 😋
Another approach, if you dont want it to be static, could be to use a ScriptableObject to hold the data, and then the few classes that need access to that data can use a [SerializedField] so nothing outside can access it, or maybe a getter-only property, I guess it depends on your goals and design
If it's a singleton, your actual instance probably shouldnt just be public
In reality, you would have to try to mess it up for something to go wrong. But better practice would be return the instance
Someone know why if I have this code attached to a weapon when I hit one enemy it does what is supposed but if I hit other different that is a copy it says that there is no skinnedmeshrenderer attached?
GameObject target = hit.transform.gameObject;
if (target.GetComponentInParent<EnemyTakeDamage>().hitPoints >= 1)
{
target.GetComponentInParent<EnemyTakeDamage>().Damage(1);
}
else if(target.GetComponentInParent<EnemyTakeDamage>().hitPoints <= 0)
{
smr = target.GetComponent<SkinnedMeshRenderer>();
Mesh bakedMesh = new Mesh();
smr.BakeMesh(bakedMesh);
Destroy(target.GetComponent<SkinnedMeshRenderer>());
target.AddComponent<MeshFilter>();
target.GetComponent<MeshFilter>().mesh = bakedMesh;
target.AddComponent<MeshRenderer>().material = Blanco;
Slice(target);
}
Its like is Destroying before baking but only for the other enemy
and the skinnedmesh is their own so idk
How do you favor to keep your runtime objects?
Separate manager/controller classes or not?
For example items, buildings, plants, npcs, characters, enemies, etc. in a city building game
A manager class which contains some general methods like Add, Remove, GetAll, GetById
Theres this script on the Weapon, the enemies have a script EnemyManager each one but nothing related
Hello,
I'm trying to use the new Input System (Device -> ActionsAsset->PlayerInput Component->Script).
I use it like:
public void OnJump(InputAction.CallbackContext context)
{
float inputJump = context.ReadValue<float>();
if(context.performed)
{
Vector2 inputVektor = new Vector2(0,0);
inputVektor.y += inputJump;
Vector3 movementVektor = new Vector3(inputVektor.x,inputVektor.y,0);
transform.position = movementVektor * jumpSpeed * Time.deltaTime;
}
}
My problem is, if I'm creating a Vector2 and Vector3 inside the function for jumping, it always resets the player to position 0,0 and then it adds the jump.
Sorry if its hard to read, I'm writing this on a smartphone but I can fix the text formatting later.
How can I create the vectors and create normal actions like jumping, moving etc. without always resetting the player to 0?
Thank you in advance!:)
Should I use velocity.magnitude or sqrmagnitude to determine how fast an entity is moving?
Need to use the velocity to evaulate a curve in which to spread footstep sounds out on
There's a bunch of other event interfaces which may help like IPointer events, and plenty of other drop/drag events
all the interfaces on the left side task bar there
yeah I'm using them in the drag script IPointerDownHandler, IBeginDragHandler, IEndDragHandler, IDragHandler
If you need more information beyond if and what object is being dragged, then it will probably be in the OnDrag event
I have a bunch of characters that do an idle animation. I would like to use cycle offset to make the animation start at a different point in time. I created a parameter called "idleOffset" on the animator and set it to a random value between 0 & 1 in the Awake function. I can see that the parameter is indeed set to a random value for each character but still the idle animations all play at the same time. Anyone knows what I am doing wrong?
Idle is the default state, I don't know if that has anything to do with it
Not sure what I'm doing wrong but this OnDrag isn't working
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
public class ItemSlot : MonoBehaviour, IDropHandler, IDragHandler
{
[SerializeField]
private TextMeshProUGUI itemsCountDisplay;
[SerializeField]
private List<GameObject> itemStack = new List<GameObject>();
private void Awake()
{
itemsCountDisplay = GetComponentInChildren<TextMeshProUGUI>();
}
public void OnDrop(PointerEventData eventData)
{
if (eventData.pointerDrag != null)
{
eventData.pointerDrag.GetComponent<RectTransform>().anchoredPosition = GetComponent<RectTransform>().anchoredPosition;
itemStack.Add(eventData.pointerDrag);
itemsCountDisplay.text = $"X{itemStack.Count}";
}
}
//Trying to remove items from the stack when dragged out of the slot (not working)
public void OnDrag(PointerEventData eventData)
{
if (eventData.pointerDrag != null && eventData.pointerDrag.GetComponent<RectTransform>().anchoredPosition != GetComponent<RectTransform>().anchoredPosition)
{
itemStack.Remove(eventData.pointerDrag);
itemsCountDisplay.text = $"X{itemStack.Count}";
}
}
}
I'm not seeing where you're actually changing the position of any element when you're dragging
Generally, anything visual with dragging is just fluff. As soon as you're dragging something, the eventdata is populated with the object that's being 'dragged', which is then coupled with the OnDrop event
Should really read up on the IDragHandler docs and see how it's being done there
I think im failing to understand something here... Why does this code log "90" then "270" back and forth, instead of "90" and "-90" back and forth? Is it just something with how rotation.eulerAngles is stored or am I just doing something dumb with the sign?
var r = transform.rotation.eulerAngles.y;
if (someVec2.x < 0) { Debug.Log(r + " | " + Mathf.Abs(r)); r = -Mathf.Abs(r); }
I would imagine Mathf.Abs is always supposed to drop the sign, so even if I passed -90, it should return 90, but why is the log for both "r" and the math operation returning just 90 and 270 specifically?
-90 is 270. eulerAngles gives you values from 0 to 360
You also likely shouldnt use Mathf.Abs because of that reason
Is there another way to always flip the sign so -90 just becomes 90, and then -90 again instead of 270? Aside from maybe * -1 on the value, or would that produce the same problem? Do I have to do some kind of eulerAngles conversion or division on the 270 before applying it?
Hmm, alright ill play around with that, thanks btw
If the value is way below -360, u can also do value % 360 then add 360 once if its still negative.
dont know if theres a function that already does this but i havent seen it yet..
you could also just do value % 360 regardless if its negative or not, then add 360 if its negative. Thatll ensure a value between 0 and 360 with the same correct angle everytime
I want to be able to access singletons in my code (managers/repositories etc) but I want to keep things ready for dependency injection, but not use it yet. I'm trying out creating a static class that stores a list of interface types and the object that derived from it. The singletons register adding their interfaces and themselves as the object to the list. Then other scripts can then use a Get to get a ref to the obect as the interface. So in the awake functions i can get the singleton by ServiceClass.Get<ITimeEvents>() to get the timecontroller singleton but with only access to the need events that are needed by the requesting class rather than the whole TimeController. Does this seem like a reasonable implementation?
I am trying to adjust the smoothness of the currently selected material, but its grayed out. How do I fix this?
This may be what im looking for, thanks again
You're using the default material which can't be edited. Make a new material and apply one of unity's shaders to that instead.
What is a default material?
If you don't select a material to add to an object you're rendering, it will use that instead
or it will instead apply that magenta (w/e color that is) error texture
Oh I see. How do I convert this default material into a materail that uses unity's shader instead, or do I have to remake the material from sratch?4
right click into the asset menu and create a new material, then should should be able to change what shader to use on it and its settings
unity supplies a bunch of shaders already like you see there
The problem is that the materials come from an asset.
You can't edit the material, because then you'd need to edit the original asset, or something
You can, however, duplicate the material
this'll give you an identical copy that is not part of an imported asset
all of the stuff in that fold-out menu were produced from that imported model
I use Rider for breakpoint debugging, and I'm noticing that if I disconnect the debugger (pressing the "stop" button), Rider won't be able to re-connect to Unity again. Any future connection attempt will show a "Waiting for target to get ready" message that never goes away.
My only surefire fix so far is to close both Unity and Rider. It's as if a resource (like a port) on one or both ends gets consumed by opening a debugging connection, and it never gets cleaned up.
Anyone else run into this and have any tips for a faster workaround? I'd be curious to understand what's going on under the hood here.
For context: I'm on MacOS 13.4, Rider 2023.1.2, Unity 2022.2.21f1
Not really sure where to put this, but I was wanting to have a ragdoll be dragged around like in the gif link. But I just want to be able to have the ragdoll be dragged around and still have it be a body, rather than it doing what it's doing now.
I've been trying to understand the documentation, looking up forums and tutorials but nothing I can find seems to be a solution.
Thanks in advance
https://gyazo.com/2b45a1ddd6de132a301f008d353d8c1d
I mean a body as in one that doesn't look spaghettified, like what its arm's doing
sounds like the joints are stretching too far
what kinds of joints are you using here?
Using CharacterJoints, the default when you use Unity's ragdoll creator. The "springs" are set to 0, so I'm not sure if that's the maximum (it says 0 means infinite but idk)
you also have to set limits for how far they're allowed to move
I've tried setting the limits to 0, 1, 1000 etc but doesn't seem to work
I've never done ragdoll physics before and the documentation and tutorials on it seem very limited. Whether or not I'm searching with the right keywords, not sure
Because a ragdoll is not really a one specific thing. If you look at your rig, you'll see that it just adds a bunch of rbs, colliders and joints.
Yeah I see that. What would I need to do to keep them locked together? I saw something about spring joints but I don't know if they'd provide a better alternative or not
No clue. If anything, character joints should be more suitable imho. Never messed with them though.
youll need ConfigurableJoints if you want true customization of ragdoll movement
Regardless of what you do, the joints will try to snap back to its connected body if it goes too far past the limit
did you use the Ragdoll Wizard?
Ah ok, thanks. By the joints snapping back, are you referring to the ConfigurableJoints or the CharacterJoints?
Yeah
I dont believe character joints have a limit for how far they can move, although not too sure
any joint will do this
its quite a pain, im still fine tuning to see if i can fix it for my character
the problem is the linear limit spring has no max force, so im unsure if it really can be fixed
I’m tempted to possibly try having a parent object and having that be dragged around instead, but I want to avoid that if I can
But yeah I’ll have a look into those joints and see if I can get them to lock in
how was this movement done, now that im looking at it this really shouldnt have problems with joints stretching
oh the video loaded, u were dragging it around
I've gotten pretty good ragdolls with fast movements
in my case, I used a FixedJoint (or was it a ConfigurableJoint with everything set to a strict limit? gotta look) to attach the ragdoll to another character
Ok well yea if you're gonna drag the joints around they're gonna break..
Move it with physics u wont have this issue
it goes crazy if the enemy shoves the ragdoll into the wall
i need to turn off wall collisions while in that state..
fixed joint works, i use it for grabbing although im also trying to do climbing which is become a problem
i had a REAL fun time figuring out how to correctly align the ragdoll for the grab
did you use a separate body? thats what i do
my character itself has no animations, it just copies them
i'm using the PuppetMaster asset to manage enabling and disabling ragdolling
it creates a simplified copy of the armature
then it either drives the copy with the original (non-ragdolled) or the original with the copy (ragdolled)
I’m guessing applying a rb.applyforce (or whatever it is) to the joint would be the solution?
ah my character is perma ragdoll, an "active ragdoll" apparently is what its called
will it cause any problems if I have a script who deletes itself?
sounds fine
Destroy just signals to Unity that the Object should be destroyed
if you have a joint, itll be attached to an object. Yes move that object with phyiscs
it doesn't die until the end of the frame
I mean it's static class 🙂
I'm concerned that JIT will blow up my computer
expecting script and not getting it
you mean deleting the actual cs script from your computer?
yes
@lean sail @heady iris thanks for the help 🙂 I’ll see how I go with it
what
well, in fact I want to delete whole directory with scripts, metas and so on
it should be fine but once its compiled i dont know how you'll do that
i mean once built
well, yes, I am assuming it recompiles here :p
it's just an editor script who is meant to be run exactly once and then get deleted. and I didn't want to bother user with it
just curious what you're even doing? seems like everytime u are up to something very niche lol
if its a 1 time script that u dont want after it runs, why not just run it and delete it yourself
template for a unity package
it has config SO, and you click one button and it converts everything automatically - renames folders, removes unneeded stuff, renames asmdefs, etc
What if the user might need to run it again?
forget the user, what if you want to run it again lol
🤔 🙃
the only time ive heard of or even thought of self deleting scripts was in malicious programs
well at the very least I want to give them an option of self deletion
I'm not really sure if I need that, but I just want to
or actually maybe you're right, I just won't delete it
user will delete it if they don't need it anymore
That's not how C# or any programming language at all works.
Your code gets compiled into an assembly and run from it. The script is just a text file.
well I don't really know, that's why I asked 🙂
critically, the script file on your computer doesn't really matter
it's been compiled already
and everything goes away when you recompile
JIT compiles from IL, not from actual C#, right?
yes, because otherwise, you could discover that your code is actually invalid
Yes. But I don't think there's any framework/engine or compiler that executes the code directly from the code file.
alright, sorry for confusion then
it would be very weird if you got a compile error only when you tried to run the code
don't modern IDEs prevent compile errors completely by just screaming at you every time you have them?
That doesn't prevent you from running the compiler.🤷♂️
And what if you didn't use an ide?
irrelevant
❓
you couldn't compile your project in the first place
it simply Would Not Run
JITing does not mean you lex and parse your code at runtime
it's just the just-in-time generation of machine code
You could write your code in notepad and launch the compiler from a command prompt 🤷♂️
you may be mixing that up with dynamically parsing and executing C#
which you can do (scary)
the lexer turns the text file into a token stream; the parser interprets the tokens
where the IL actually lives in project?
nvm it's Library/ScriptAssemblies it seems
curious what will happen if I delete Library at runtime 
You probably won't be able. And even if you did, nothing bad would happen. In the worst case, it will crash when trying to load a library on demand.
At best it would not need to load a library(since they're loaded into RAM), so nothing would happen.
But I think the OS might block the loaded files from being deleted.
yes this is the most likely outcome
anyway I will never need to do that xD
was just curious
Windows loves doing that
On Linux, deleting the files would do nothing if there was still an open handle
Heya, bit curious about something, I wanted to test that new Netcode for GameObjects thingie for a WebGL game, but I remember hearing that it wasn't supported, but on the documentation i can find nothing about that. I also heard though that there are alternatives? Do any of you know about any of this?
what is the difference between doing
#if MY_CONDITION
// stuff
#endif
and
[Conditional("MY_CONDITION")]
// stuff
other than Conditional is way less universal? am I missing something?
can the attribute use inside a method? i think it cannot since it doesnt specific where to end
that's what I'm saying. it's WAY less universal than #if
and why would one use this attribute when you have #if
[Conditional] methods still exist when the program is compiled
and not all things can have Conditional applied to them
Only the calls are stripped
🤔
so... if I do #if, and call a method elsewhere, I might just get a compile error, and with [Conditional] I can call it anywhere and it will be fine
as far as I understood it
Yes
makes sense
I even have a library that uses both, Conditional to strip the calls to the methods, and #if to strip the methods completely
this has a nice explanation which I couldn't google up myself, thanks
not really a code question, but right click in your project files. Create > Scene
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadScene.html
And to make it a code question, heres how u load it 😄
so i have to redo everything again
well u want it to be a different level no?
Did you expect anything in particular to be in the scene?
I have a bunch of characters that do an idle animation. I would like to use cycle offset to make the animation start at a different point in time. I created a parameter called "idleOffset" on the animator and set it to a random value between 0 & 1 in the Awake function. I can see that the parameter is indeed set to a random value for each character but still the idle animations all play at the same time. Anyone knows what I am doing wrong?
Idle is the default state, I don't know if that has anything to do with it
are you actually using that idleOffset
or you are just setting it to a random value but that's it
I've checked the parameter checkbox next to cycle offset and set it to idleOffset
what have you tried. do you have any code?
i have code that it shoots
okay, how about showing any code where you tried to make the bullet move
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public float bulletForce = 20f;
public float fireRate = 0.5f;
private float nextFireTime = 0f;
void Update()
{
if (Input.GetButton("Fire1") && Time.time >= nextFireTime)
{
nextFireTime = Time.time + 1f / fireRate;
Shoot();
}
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody bulletRb = bullet.GetComponent<Rigidbody>();
bulletRb.AddForce(firePoint.forward * bulletForce, ForceMode.Impulse);
}
}
thnx
this still floods the chat but sure
can you show the inspector of the object with this script
and are there any errors in the console?
try increasing the bulletForce to like.. 200
the bullet is spawning, right?
can you try changing this
bulletRb.AddForce(firePoint.forward * bulletForce, ForceMode.Impulse);
to
bulletRb.AddForce(Vector3.forward * bulletForce, ForceMode.Impulse);
just temporarily. testing
are you able to record a video of what happens?
also select the bullet in the hierarchy once it spawns so I can see the inspector
show the bullet inspector please
the full thing
this also makes it crash my game
and show the console
thnx for clearing that up i did not know what stacktrace meant haha :))
you.. destroy bullet or bulletPrefab anywhere?
uhm no i don't know how that works
im a bit new xd
is it just Gameobject.Bullet.DestroyObject
cuz this is
this code
i dont see Destroy anywhere
yea true
i dont know how to xd
i tried before but it doesnt work
so i have to do
Destroy(gameObject);
or that with the bullet name
you don't
never mind. i dont know why you have that error, and not sure if it's got anything to do with your bullet not moving
same i legit don't know haha
show me your Bullet script?
oki
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public float speed = 10f;
public float lifetime = 2f;
public int damage = 1;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
// Set the bullet to destroy itself after the specified lifetime
Destroy(gameObject, lifetime);
}
void FixedUpdate()
{
// Move the bullet forward based on its speed
rb.velocity = transform.forward * speed;
}
void OnCollisionEnter(Collision collision)
{
// Check if the bullet collides with an object with a health component
Health health = collision.gameObject.GetComponent<Health>();
if (health != null)
{
// Deal damage to the object
health.TakeDamage(damage);
}
// Destroy the bullet upon collision with any object
Destroy(gameObject);
}
}
can you show me the inspector of the bullet prefab
the bullet prefab
the gameobject that you drag into bulletPrefab
did you drag something from the scene, or from the project window
is that the one you drag into the bulletPrefab variable
you could be making it a Prefab. It shouldn't be in your scene
idk what prefab is man
otherwise it's going to call Destroy(gameObject, lifetime); from Start
then you should have started with some unity basics
Prefabs are a special type of component that allows fully configured GameObjects to be saved in the Project for reuse. These assets can then be shared between scenes, or even other projects without having to be configured again. In this tutorial, you will learn about Prefabs and how to create and use them.
true but i came this far without knowing what it is xd
go through that first
you need to learn it. that's basic stuff
that's why you're getting the error
once you've made a bullet prefab, you set the speed in its inspector to 200, then you see if it makes a difference
funny how you call it bulletPrefab, but it's not a prefab
next time you ask in #💻┃code-beginner
Prefabs are the building blocks of any Unity project. Prefabs are essential for saving developers time, and maximizing efficiency. We go over how to create a prefab, how to instantiate one in code, and show an example of prefabs in action.
You can check out reviews of Unity at TrustRadius.com.
Music by Lukrembo
maybe this will make it clearer
since the text one might be hard for you to understand
I know how to achieve blending two textures using shaders, but does anyone have a link to a tutorial that explains how to blend two textures using some sort of input? Like say I want to paint a dirt path on the ground, how would I achieve that(assuming I'm not using terrain)
Note that I'm not sure how you'd do the painting part -- I've done similar things before, but not actually implemented a painting tool
(it was automated as part of level generation)
I'd make a shader graph with three Texture2D properties.
Two would be the input textures, and the third would be the mask.
Sample the two textures normally, then mix them with a Lerp node. The t input on that node would come from the mask texture
mmm
yeah that makes sense, but I guess I'd have to find some way to paint onto the mask
and it'd have to translate onto the uv properly
is it possible to regulate an object to a prefab? Like just tell it "Hey, from now on, follow all the rules of this prefab"
Like if you make multiple objects, then do the prefab
no, you can't retroactively make something a prefab instance
other than by making the prefab from it
Tragic
I'll have to remember to do that in the future
time for my file system to become even more unavigable

you dont want to know
shame, shame
could you not make a one-time editor script that scans through all the game objects and instantiates prefabs and deletes the game object?
you can make editor scripts????
yeah, i had that thought
Hi! quick question: how does ScreenCapture.CaptureScreenshot behave in a webgl build?
(i never know if i should shoot my shot in #archived-code-advanced or not)
- On pausing, i want to disable the entire game but also keep the last rendered frame in memory to use it as long as the game is paused. What sort of magic runes do i need to type to achieve this?
How can I use IDragHandler to remove an Item from a list?
I have a list of gameobjects and when I click and drag a gameobject I want to remove from a list
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.
Just try setting
Time.timeScale = 0
To unpause
Time.timeScale = 1
im making a card game and obviously want each card to function differently but I dont know if I should make a script for each card or use scriptable objects somehow
does anyone have any tips
Anyone good at math? I'm trying to fill a three dimensional matrix evenly with nodes... so I iterate through say 16 positions that I try to get via this script... but the Z value I cannot figure out how to retrieve, based on the input parameters...
you'd still probably need to write separate code for each kind of card
yea thats the problem
so if you're filling a 16x16x16 cube, you want iteration to range from 0 to 4095 ?
4096 = 16*16*16-1
if i use scriptable objects i cant really write specific code
- Thank you very much but there's a reason why i didn't go with this approach
but wouldnt having a lot of card scripts stored in memory be bad for performance?
yeah I guess so... I mean Ideally it would work for any value right
no
im planning on having a lot of cards
do not think about performance at all at this point
ok, so you need to correctly turn the 1D index into the X/Y/Z indices
you have roughly the right idea here
I believe so... it seems to be working fine for the x and y values I believe 🤔
What can I do about this
for access 1d flatten array with index i1,i2,i3.....
(i1*size(i2*i3*i4*...)+i2*size(i3*i4*...)*i3*sizeof(i4*...)*....)
but wait how would I store the card data if its a script?
like art and stuff
i cant just insert them in the inspector
Is that something I need?
I feel like I have tried every possible operation
maybe you should stop and think about how the math works...
suppose we're doing a 10x10x10 cube
i is the index
when i=1, you get [1,0,0]
Y and Z are both at zero right now
Oh, nodesPerSide is an int, so you were already getting a floored result
i see
but let's go through the example anyway
when i=10, you get [0, 0, 1]
X = i % 10
Y = i / 100
Z = i / 10
that sounds reasonable
What is the problem?
You can add a texture2d or an Image to a script , but you can use a scriptable object
I guess you also need to take Z modulo 10
so that when you hit i=100, you get [0, 1, 0]
rather than [0, 1, 10]
(i1*size(i2*i3*i4*...)+i2*size(i3*i4*...)*i3*sizeof(i4*...)*....)
i1=index/size(i2*i3*i4*...)
i2=index/size(i3*i4*...)-i1*size(i2)
i3=index/sizeof(i4*...)-i1*sizeof(i2*i3)-i2*sizeof(i3)
how you get back all the indice from a flattened index
yo!
How do I use initiated objects on another if statement?
where the else is I want to destroy the instantiated object
um its in an else that means its not instantiated
its local to that if statement
yeah
ik
is there any way to destroy the instantiated object on the else statement??
its instantiated in the if statement, how could you expect to destroy it in the else, if it hasn't been created yet
not unless you stored it in a non-local var
yeah it doesnt make much sense
var
ok
I'll do that
well I knew that it wasn't making any sence
please don't tell me the obvious
no like
a private member
private MyType
ik
oh wait
not like private var name?
oh ok
var is for local memember
you can try goto and go into the else statement but the normal contrl flow is execute either one of these two group of statements.....
I haven't used var that much before so I'll go look it up a little
but the object wouldn't exits in the else statement anyway so why bother
By reusing belt, assuming it's allowed by the scope of your code
Considering I don't see it being defined anywhere, I assume it's class-scoped
Yes so you can just use it anywhere in the class
The question is if you assigned it at that point
Otherwise it will be null
So you need to make sure of that
What is the options for this
if it's null you cant destroy it
you can't call Destroy() on a null object
yes we see that
if you dont assign it prior to the else you're just gonna get a NRE
yeah ik
yep
so how do I do that
var?
we don't know why you are wanting to destroy this in the first place
that's more important
as this smells like XY issue
ok I'll explain the code a little
this code is part of an inventory I made. So the if (slot.ItemData != null) is the slot it self and checks if it's not a null
on the else statement
it is null
so if there's no item in the slot. It should delete the belt instantiated object
that's what I want
idk if that helped
but you instantiate it if itemdata is not null
so if it is null then nothing will be created
I must be asking in the wrong thread I guess
yeah
I need to get deleted
did you read? :P
the object gets added
@tawny mountain i see your code since i havent use ondrag before but your code seem works
what I'm asking is I want to somehow use the instanted object in the else statement
idk why]
which is why I'm asking
you may need to think a new and clear control flow of your program....
someone said to use var with MyType. I don't really understand what that means. And unity doesn't have a post anything about var
nvm that I thought belt was a local var
if nothing is created then nothing needed to be destroyed...
I'll give the full code
where can I post it?
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
this should explain it
this
It doesn't
you tried ?
the else only destroys if ItemData is null
yes
is using Gameobject belt correct?
it's fine, but you need to check it's not null first before attempt to destroy
it does that
not really
huh
it checks for ItemData in slot
not belt
I don't need to check the belt
you kinda do
why?
public void OnDrag(PointerEventData eventData)
itemsList.Remove(eventData.pointerDrag);
is this method doesnt work? try debug.log the name of pointerdrag @tawny mountain
I am not getting any error. But ok I'll do that
for now.. lol there can be an edge case where it can
ok
like this?
btw
the GameObject belt; is null
someone said that that is a problem and idk why and it should be
nothing
yes
and wdym then it was not assigned if is null
If I have to I'll pay someone to fix it... Grrr frustrating
yeah it's not assigned
gimme a sec
what exactly isnt working
if I've done something like this it would work
of course I don't want it to be on a timer
which is why I want the object to get deleted on the else statement (whenever there's no item in the slot)
so leave it like you had before
get rid of the local var for belt
My OnDrag method.. I have a list of gameobjects and I'm trying to remove gameobejcts from this list by clicking and dragging.
is that only one that doesn't work ?
why would you remove the item you are dragging from a list whilst you are draggging it?
I'm taking pictures. I don't want to upload the code
yes thats fine
Yes
maybe dragging an item out of a slot or something
if nothing is printed on console, that means nothing call it back
but it's called multiple time. you can only remove once
kinda makes sence why you said to check in the else statement if the belt is not null. There could be an error in the instantiation
yes on this point. Why not use OnBeginDrag ?
Because I have objecs "stacked" and When the item is dragged i want the count to go down by one when the item is being dragged
Correct
OnDrag is multiple calls
EndDrag. Drop
I'll try that one
: MonoBehaviour, IDragHandler, IPointerDownHandler => OnEndDrag then?
that works but imo OnBeginDrag would be a better fit for their use
I wonder if somebody knows how to set colors with RGBA or just to change the A parameter in TMP_InputField
<color=#FF0000>RED COLOR</color> (works)
<color=(255, 0, 0, 1)>RED COLOR WITH A = 1</color> (doesn't work)
just use hex 😛
public class ItemSlot : MonoBehaviour, IDropHandler, IBeginDragHandler, IDragHandler, IEndDragHandler
how do I?
A = 1 doesn't work in what way?
iirc alpha was 0~1
I want to implement a stat tracker into my game. I'm not sure if I should make this a singleton MonoBehaviour (maybe I DDOL it), or if it should just be a lazily-initialized POCO
Any opinions?
It will be tracking some stuff that changes very infrequently (e.g. number of times you've started a game)
yes color is 0-1
color32 is 0-255
and also some very frequent stuff (footsteps taken)
this one works, but the A is not changed
<color=#FF0000>RED COLOR</color>
I'll probably write the data out to a JSON file on quit and on a regular basis
yo null I'm sure this should be working. I just found someone with the same problem and everything worked for them https://forum.unity.com/threads/destroy-instantiated-object-on-button-press.1064576/ they just didn't realise it
ah yeah, maybe
json should be fine tbh
POCO
no need for mono tbh
Still can't get the behavior I'm looking for
public void OnBeginDrag(PointerEventData eventData)
{
if (eventData.pointerDrag != null)
{
itemsList.Remove(eventData.pointerDrag);
Debug.Log(eventData.pointerDrag);
}
}
what isn't working about it?
Neither the remove nor the debug
@gray mural you don't have an option of setting it through script instead of rich text?
this isn't about the serialization format, exactly
just the runtime object
try debug if the method is called
actually, can I just register a method to run on application start? I remember seeing that...
I just need to make sure I load the saved data before trying to use it
so I have not found it in google, that's the only method (that suggested Chat GPT) that worked
that's the shit i'm using and it works
if this is to me , it appears that it's not being called
public void OnBeginDrag(PointerEventData eventData)
{
// NOT FIRING
Debug.Log("OnBeginDrag");
if (eventData.pointerDrag != null)
{
itemsList.Remove(eventData.pointerDrag);
Debug.Log(eventData.pointerDrag);
}
}
wouldn't that jus be Awake 😛
so that's for the whole text I guess ?? I am changing just one letter
well, no, since this isn't a MonoBehaviour
and, even if it was, it's static
ha
ah fuck
jinx
ok then it makes sense
lol
yeah, this is what I was remembering
so I'll deserialize the data at launch, then periodically serialize it
so that if you get mad at my game and shoot your computer, you won't lose too much data
imagine having the ability to read documentation instead of trusting google and chatGPT

oh, yeah, hold on, I kinda understood
but finding documentations is quite difficult
no it is not
for me it is
google 'unity what I want to know'
Thats why a unity page exists with a search function xD
i would suggest getting better at it
and you didn't even use the unity keyword which I do not understand
rather than asking a spam machine to hallucinate an answer
yeah, the answers are quite bad, but it still may know something that google and documentations do not
impossible
though it should be nice to combine chat gpt with documentations
it can convince you that it knows things
this is very different from it knowing things
I can convince you that I know how to draw, but I cannot draw
wait till gpt 5 😛
it can write the whole script for you, though you then need to correct hundrets of issues
in which case it is worse than useless
if the method not being called then you may missing some important setups probably a eventsystem on scene, and you need to ask others for more further helps, i didnt use it @tawny mountain
I have an event system in the hierarchy
I think GPT is quite useful, I see a lot of appeal for it writting code when it involves small snippets, it atleast gets you on the right track really fast. But only is good if you already know what you kinda want.
fixed the problem some how @potent sleet
I figure out what I want, and then I write it
Thats naive way of thinking but ok
🤔
yes let's not argue over a hammer/ screwdriver again xD
this is wildly different from what you were saying
yeahhhh
I just figured out another way to Destroy an object
I did realise that it was instantiating a lot of objects for some reason so I just did childCount which gave me an idea to just delete all children in the parent
idk why I didn't come up with that
Chaning Alpha Parameter in TMP_InputField
is rigidbody.angularVelocity local rotation, or world rotation?
velocity is world-space, so I'd expect the same for angularVelocity!
ah, damn
then I have a problem
I'm adding torque to a weirdly rotated object. Is there a way to get how much angular velocity the object already has, in the same "direction" that the torque would increase? I'm looking for a float.
I hope it's not too confusing
Ok , I figured something out , maybe you can help get me to the finish line now... The methods are called when I try dragging the item slot , not when I try dragging the item from the item slot.. so I'll need to remove it from the item class instead of the slot class
the script is on which object?
Item Slot ... I got it removing the object now. getting the proper references and its doing what I want ... kinda sorta
ohh so don't you want the script on the items if that's what you wanna call methods from ?
I have the behavior I was after now but probably not efficient , I'll share both scripts
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.
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.
looks fine
Top one is ItemSlot
don't see any issues doing this
Thank you for your assistance , I appreciate it
One last question , what if I wanted items to start in the item slot? I can put them there by default , in the editor , but can I do that through code?
are they UI items ?
Yes
put the anchordposition to be item slot location
Images
In Start()?
sure or awake
Ok
Can I do OncollisionEnter with particles?
there is their own method OnParticolCollision or w/e
Shall I put that in the particle caster object or the other one?
everything is exlpained in the api
ok
private void OnParticleCollision(GameObject other)
{
if (other.GetComponent<PlayerStats>())
{
other.GetComponent<PlayerStats>().TakeDamage(40, "Died from Steam Burns");
}
}
this feels like it should work, but it doesn't
nothing is triggered
let me try something else maybe
its probably a parenting issue
Parenting shouldnt effect collision
well if the collider is in the child, but the script is in the parent
from a script attached to a ParticleSystem
How do I attatch a script to the system istelf, or do they just mean the same object
when I copy paste my prefab only the last pasted prefab uses the script attached to it
Im using GameObject.Find(), is that the issue?
only the last pasted prefab uses the script attached to it
What do you mean by this exactly?
what does it mean for the prefab to "use" a script?
Does field:SerializeField only work in some unity versions? I swear it worked at some point
it works on all versions of unity that support C#7 and above
[field:SerializeField]
private float maxWheelTurns
{
get
{
return ((_rotationRangeDeg / 2f) / 360f);
}
set
{
_rotationRangeDeg = value * 2f * 360f;
}
}
my code, for reference
I tried both with property and with field
this won't work on any version
it only works for auto properties
auto properties? as in get; set;?
yep.
as in auto-implemented properties that don't provide an implementation, yes
if you are providing a custom implementation for the property, it won't work, because there is nothing for the attribute to target
with auto properties the attribute targets the auto generated backing field for the property
with a custom implemented property, there is no such thing
in this case it looks like you should serialize _rotationRangeDeg
since that's your backing field
tl;dr: get;set; is exact same as get { return hiddenField; } set { hiddenField = value; } private var hiddenField;
It's not worth it to make a custom editor for every single thing I might want, that works like this
and I'd really love to have a couple of values like this, where I can change either in inspector, and they all update instantly
it should really be made easier by unity somehow :/
[field: SerializeField]
public int X { get; set; }```
is like:
```cs
[SerializeField]
int _x;
public int X {
get => _x;
set => _x = value;
}```
use NaughtyAttributes or Odin
I actually have NaughtyAttributes, how do I do it?
ShowNativeProperty doesn't seem to work
So i have a prefab with multiple objects. One of those objects has a script. That script only runs on the last pasted prefab
Idk how to explain it
actually not sure NA can do it. Odin can
But the other prefabs dont run the script
You'd have to show the code
and how you are verifying that it only runs on one of them
also please note the difference between a prefab and a prefab instance in a scene
Thanks for verifying
If you want to verify if the code is running you should use Debug.Log
it may be running and simply having an unexpected effect, or some other code is reversing its effect or whatever
Also please show the code
Impossible but lets take a look
impossible
bold claim
impossible
got it working, but get only :(((
all of them did right>
So your assertion that only one is running is false
Heyy, looking to create an object generator in a most performance effective way
Is there any way i can improve this code?
public GameObject stoneObj;
bool cooldown = false;
void Update()
{
if (!cooldown) StartCoroutine(SpawnStone());
}
// SPAWN STONE
IEnumerator SpawnStone()
{
// cooldown
cooldown = true;
yield return new WaitForSeconds(5);
// spawning
GameObject stone = Instantiate(stoneObj, transform.position, Random.rotation);
cooldown = false;
}
more logs!
no need for Update here
either get rid of update or get rid of the coroutine
you only need one or the other
This is why I said initialy that it didnt work
Oh, but then how can i keep calling the CoRoutine?
how do I make a thread here so I can group my thinlgs
void Start() {
StartCoroutine(SpawnStone());
}
IEnumerator SpawnStone()
{
while (true) {
yield return new WaitForSeconds(5);
// spawning
GameObject stone = Instantiate(stoneObj, transform.position, Random.rotation);
}
}```
When you want to repeat code, that's what loops are for. You only need the one coroutine
Should be an option on your message beside delete/edit to create a thread
Oh wooow. I completely forgot about while loops. Indeed no need for Update
Many thanks
This is why I said initialy that it
thanks
if I create a script to store data and place that on prefabs. Is referencing that script from the prefab mechanically similar to using scriptable objects?
I mean in terms of memory efficiency
where would that script actually store data if its not initialized
spawning a bunch of those prefabs would make more data than all of them referencing 1 SO
The idea is that I wouldnt be spawning the prefab
but using this script as an accessor for data related to the prefab
in terms of memory, it really wont matter. I guess the prefabs themselves might be more than an SO asset
itll be like trying to save less than a mb of memory
I guess im more concerned about whats more professional. Since I am about to make a LOT of object types. And the possibility of needing to redo it later on is a bit intimidating.
id definitely just go with SO rather than try and recreate data containers
because all those data containers u will be setting up manually as prefabs. If you have to go back and change something thats a ton of manual work
with an SO at least u can mass create them
Part of whats making the decision so difficult is that there are advantages provided by the prefab editor which could be beneficial in the long run. Like having to set up the dimensional parameters for an object can be a bit iffy, but I could make an editor to have that process be a lot more intuitive.
would it be hard to access the script on the prefab if I wanted a certain type to be selectable from within the game?
i dont really know what your intending to use these prefabs for, it sounds like you want more than just data to be contained in them
i just assumed u had an empty game object with a script on it
Hi yall I've got some unusual problem with Sprite Shapes. So basically i try to spawn bunch of collectible items using RaycastHit2D, but they end up being on wrong positions. It happens because Sprite Shapes for some reason don't update their colliders when they are off camera. When im observing gameplay through scene mode all Sprite Shapes update their colliders corectly because i see them. The problem Is that i have to spawn them ahead of camera because that would be weird for collectibles to pop into existence in front of player right 😛 ?
Well, for an example in my context I want to be able to have a configurable vehicle. Where I have a script that defines the parameters for the chassis, like the wheel size, wheel base, track width, etc. So that that data is tied to the prefab that houses the resources for the object. That way if you swap from a car chassis to a truck chassis, it will already know how to rearrange the parts to accommodate it.
still sounds like SO would just be better in that case
I've never used these so I'm just thinking out loud here. Does it update if you disable/enable the collider?
@wispy wolf mmmm im not sure, but its weird that it adjusts only when its seen
What are the advantages?
Or maybe try toggling "update collider" off and on? Idk
@wispy wolf wouldn't have bothered any of y'all guys 😛 if i hadn't tried lots of stuff
@wispy wolf I have thought about manually adjusting collider to sprite shape but there's also a problem... Sprite Shape uses splines and polygon collider2d uses list of x,y Vector2s. Have you got any experience with splines?
really just try it, you're recreating an SO by using these prefabs with a script on it purely for containing data. Editing these scripts are going to be way harder
Or maybe should i ask this way. Does anybody know how to get [x,y] points from splines in a manner that for eg. polygon collider 2d has them stored? If i could only figure that out i would be able to copy these points and manually update collider. I'd be VERY thankful.
Yo. I've got a problem with projecting a webcam stream onto a texture. I can see video input projected onto a plane, but it stutters every 1-1.5 seconds. Everytime it stutters it seems like the light gets readjusted so I suspect its autofocus. I used webCamTexture.autoFocusPoint = null; but it didnt change anything. Its a shitty old tracer webcam, but when I tested it in discord and the windwos camera app, the stuttering didnt appear. Has anyone encountered this problem?
How do you suppose it will be way harder? Currently I find the process of dragging the skinned meshrender from my fbx prefab to the scripable object quite frustrating.
You gonna need both SO and Prefab.
By example:
One for an actually tire in the the scene that have values such as speed, hp, etc.
One for the concept of the tire such as Name, Quality, Recipe, etc.
The process I am using never has me instantiating my prefab, so I dont particularly see why the data needs to be separated
@swift falcon there was a method to rebuild collider at runtime, they were even showing it in their demo video
@twin hull where?
fuck if i know ahaha, i'll try to find it i guess
If you are not instancing anything and everything has no value specific to an instance, you want SO.
Both, I doubt that you will have a stateless car.
what do you mean by stateless
There is no value that change
The way Im approaching vehicle simulation is to write scripts that build physics systems from rigidbodies and joints. These scripts are that which handle the state of the object.
I just need a definition for the vehicle's values that I can slot in the "customization menu"
The actual piece will be a Prefab, but the concept of the piece will be a SO.
The SO can even reference the tire if you want as a game object to say what object is supposed to be spawned in the word
@twin hull ohhhh i think u just helped me i found something on Google thx 😄
An SO should be stateless.
I feel like you misunderstood. I have an object that handles the state already, it is the same object which builds the part. What that needs is a definition to be fed, which is planned to be done so through whatever means of definition I choose. Currently prefabs seem appealing since they make it easy to assign components from a variant of the FBX prefab, I could even add an editor with gizmos to better visualize the properties. My primary concern is how easily accessible these prefab scripts would be from within the game.
I dont see how assigning components from a variant is any easier than just having an SO for the tire
That SO can store a reference for what object to spawn. Not the object in the world
huh? the SO wouldnt have a specific object to spawn, it has the instructions for how to build something.
Accessibility shouldnt be an issue regardless of how u code it, the issue comes when you want to make a change and you have to edit a bunch of prefabs rather than an SO
I would only need to edit the prefab relevant to the part. I dont se how having a "heavy strut" and "light strut" scriptable object is significantly different from having them as prefabs that I enter to edit the scripts of.
What do you mean instructions to build something
Currently, I am trying to work with scriptable objects. I store the skinned mesh renderer that comes with my FBX prefab so I can assign it to one of the objects that my system generates.
SO is litrerally use as definition in most case. A definition is stateless.
This is expected. You store a Prefab. The FBX is a prefab.
Definition is most of the time responsable to construct its world representation.
Im not storing the prefab
im storing the renderer on it.
if I stored a prefab with multiple renders I would have no way to access them correctly.
An FBX is a prefab
yes
So you are storing a prefab
Bad idea.
are u not trying to spawn the whole object? can you describe what you're this is actually for in the game because i still dont know what "instructions to build something" means in your game
Store the prefab and get the renderer.
But you should spawn the whole object
Ideally, divide your object in multiple part.
Maybe you exported one FBX with everything.
But divide everything in multiple GameObject.
my parts often need substantial modification before they can be represented properly, if I simply instantiated my prefabs im risking a frame where everything looks wrong.
It is not a reason to do what you are doing.
Find an alternate solution.
I need to break up their construction into the creation of objects on which to place components. There are serious physics issues with scaling physics components.
I am animating my parts via physics, so I cant simply put a rigidbody on a bone. I need that bone to be a child object of the rigidbody.
thus I need to assemble the whole part manually.
I do the samething. I have weapon which need to be link with SkinnedMesh of the player.
I still use prefab.
does your weapon function physically with numerous joints
it cahnge nothing, it could as well be.
You can do complex setup ame with using prefab.
Anyway, you want SO for your orginal issue.
For sure.
how do you propose I properly scale the strength of a spring if its just a prefab I instantiate...
what do you mean scale the strength of the spring?
you havent really described much of what your game is actually doing, so we dont know what effect this is supposed to have
this is a part of one of the scripts in charge of "Generating" my part, its dependent on variables that come from the vehicle data. The idea is that it handles the building, rebuilding, and state of the part it represents.
I feel like it would be painfully more difficult to manually make prefabs for every part where I assign the rigidbodies, colliders, renderers, etc, one by one.
Such probably would be the case if dealing with components post-creation wasnt so finnicky.
What I am curious about is whether it would be practical to make scripts that I can assign to a variant of the imported FBX prefab, where I can define which properties to use in order to guide generation.
If I instantiate a strut with rigid bodies already on it, that isnt going to behave as I expect if I try to set its transform properties.
im asking about what this effect is in your game. What is the goal in your game itself that the user will see happen?
Well, ideally each vehicle is defined by some collection of data which says which parts it is made of. Those parts are read as instructions when the game is tasked with building the user's vehicle.
The parts the user selects will be the SOs or prefab scripts.
as the developer, I feel that I could make the process of setting up this data easier by doing it from inside of the prefab of the part, where I can have easy access to the prefab's components for assignment.
You can get the same result by doing it as you are, but whatever component you store on that prefab, you can store that in an SO
if you feel its more accessible by making it a prefab then go for it. It will just be way more annoying when you want to change something
what would be difficult to change though
that depends on your design and how you choose to implement things. Kinda hard to make an example thats related to what your system is. I imagine if you want the user to select between different materials though, you'll have to make a new prefab for every single tire variation of materials
you could code it in a way where u dont do that, but with SO you can just store the list of materials already
https://paste.ofcode.org/DMyn4yUTk57BwcRJrdc6DY
i have made an ai script but sometimes it gets randomly stuck and i have no idea why can someone help me please and thankyou!
btw the reason why im not using unitys navmesh is because im on procedural terrain
you can do the same things without scriptable objects, itll just be more annoying in some cases. It will still work but design changes become more annoying
Yeah, I have thought about the varying materials possibility, I just thought I would do that similarly to tuning, where paint jobs arent vehicle-specific, and would likely be applied after the base material.
yea so you could code it where it isnt an issue, but that list of materials is going to have to be stored somewhere else then. Where? well either another prefab, or another script
I cant really say itll be bad because you could design it really nicely, but at the end of the day scriptable objects could just store it by itself
But I am in the same boat, the only thing stopping me from powering forward with scriptable objects is the frustration of extracting components from my imported prefabs. I guess I could make it so I just assign the mesh and material, but it felt like I could smoothen my workflow by referencing the components that the prefab comes with.
Plus, when I set the wheelbase and track width, I really have no idea what thats going to look like when it generates, so I thought I could make an editor with handles that render to assist.
that way it renders inside of the prefab n stuff.
It would seem to indicate your JSON payload is not correct somehow
You sure JsonUtility can handle the type you gave it? Check the actual JSON string it produced vs the API spec.
you can create navmesh for procedurally generated environemts. Following code did the trick for me:
var navMeshSurface = floor.GetComponent<NavMeshSurface>();
navMeshSurface.useGeometry = NavMeshCollectGeometry.PhysicsColliders;
navMeshSurface.ignoreNavMeshAgent = true;
navMeshSurface.BuildNavMesh();
AAAAAAAAAAAAAAAAH
How can I prevent this from resetting
assigning 24 every time is gonna kill me
Oh thankyou i never knew this!
a list of textmeshes
and I assigned the objects
24 of them
and all of a sudden the thing reset to 0
no need to say that u could had just ignored what i said 🤷
assign them with a script , assigned how?
you have to be more specific
You do not need to use a prefab, it just that if you want to use a prefab, you should not reference a component inside it. You could easly, just make a function on your SO that edit your car. Adjusting whatever setting it needs.
public class MyPiece : ScriptableObject {
[SerializeField]
private GameObject tire;
[SerializeField]
private float friction;
public void Assign(Car car) {
car.SetTire(tire)
car.SetFriction(friction)
}
}
Also, you can make an Editor for a SO.
check references?
what would an editor be able to render, the point would be that I could render gismos to visualize where parts would be compared to the vehicle's body
Anything that you want. But the fact that the part have a location give you a hint as why I say you need to have both an SO and a Prefab.
what location
visualize where parts would be compared to the vehicle's body
ah
You will need an object in this instance, that would be the actual part. (Prefab)
The SO would be the concept of the part.
Think of this as a class versus an instance of a class.
You can also see this as the following:
You want to buy a fish in the market. In this sentence, the fish is a SO. It is stateless. (Price, Name, Description)
You have a fish in your hand. In this sentence, the fish a prefab. It has a state. (Size, Smell)
The SO is something that every fish share while the prefab is something that is unique for each fish.
In your case, that could be something like:
(SO)
Name: Golden Tire
Requires: Golden Engine
(Prefab)
Position: (0,0,0)
RemainingDurability: 0.25f
Show the full script
o-o I think theres a massive disconnect here
Maybe, but you will need to explain better if you want more help.
I didnt do anything I didnt even start the script
Is there a way I could just have a small window in the inspector for the scripableobject which renders the vehicle's mesh, even if just in wireframe, and any handles I want?
Yes you could.
That would be a lot of effort.
But not impossible.
The best would be to use the scene.
Or a temporary scene.
like a prefab ._.
No, that would need to be your whole car.
If you want to see how your piece looks in relation to your car you will need to construct your whole car.
Otherwise, how would you know what it looks like on your car if you have no car ?
The radius of a wheel is not a property of the wheel, its a property of the chassis. So I only need to draw a circle to represent that value where it would be on the car.
Then, you can have your SO (Tire) renderer something on every car of the game whenever it is selected.
You could also have an editor on the car instead.
That would renderer every piece it can have.
I already have that, the point would be for it to be visible as you update the SO
@topaz oceanEveryone that makes vehicles just draws the wireframe using Gizmos in the scene view in the editor
Is there any reason this isn't good enough?
because I will have to ping pong between editing the SO and previewing the change.
I dont see how thats much different from not seeing it at all and just waiting for it to generate
because technecally thats what I already have
Is it not enough ?
that's the standard. Everyone does it that way
^
But you can already preview the change
You can also have multiple inspector if this is an issue.
when I select the scripableobject the gizmos dont render
And lock one of them.
There is a variation that renders all the time.
that hijacks other gizmos
You can also control the visibility of a gizmo.
You can also have an other inspector and lock it.
You could also have a custom editor on the car that can edit a scriptable object directly from it. (If they are proprities of the car)
Im going to attempt to just add an inspector window which draws the mesh and params.
it will give my scriptableobjects some heft and make setup more intuitive
Good luck.
how can i get this greyed value? sizeDelta.y return 0
it's the height of the rect
you get it with .rect.height
well youre wrong
So anyone knows how can i get it just for read?
they literally just said how?
#archived-code-general message
Please elaborate on how it's wrong if you think so
are you trolling lol ?
Learn about rectTransform
man didnt even read the answer properly and still tries to act smart
Hmmm seems like i need to learn about rect transform hah, my apologies
Sorry to jump out of the topic, but I wonder, is there anyway to access the list of sprites, from a Texture set as multiple, without using Resource or Asset Database ? (In code I mean).
Right now, I don't see any other way of doing it, and I find it strange that's its not accessible !
Thank yooou !
texture set? what's that?
The wording was a bit clumsy, I meant the property of the Texture2D which is "SpriteMode : Multiple".
Basically, doing so
Sprite[] sprites = Resources.LoadAll<Sprite>(texture.name);
Without using Resources.LoadAll which is not optimal at all.