#archived-code-general
1 messages · Page 426 of 1
Find is a pretty garbage method, you should never seek objects by name or string
Compile errors because you're like coding without a configured IDE..
hard to spot errors if everything looks k
then why is it all white?
you just proved my point
Compile errors because you're like coding without a configured IDE..
if you cant see what members you are able to access within a class there is no point in coding with a text editor
I went through the trouble of configuring it to unity!
if that were the case it would be underlining red
didnt we do this already
i thought i did!
well then make sure it doesnt say Unloaded although that assembly is probably not related
it needs .NET Desktop for some reason
huh ? where
when I try to fix the unloaded
go to unity close VS, regen project file, open script from unity again
are you sure the Unity Workload is installed in Visual Studio installer
yes!
one second
running through it
oh boy, I had to drag the instance to the object slot manually
this is rubbish
demo of what I mean
how do i get it so it does the "get instanitation" automatically
which instantiation ? you haven't shown that
Awake only works if the object was created by the time that Awake runs
and even if the other Instantiated it at Awake its never guaranteed the order
at very least you'd do
Awake() Instantiate
Start() Find
PlayerBase(Clone)
either way Find is still garbage and you shouldn't do it this way
btw next time post in #💻┃code-beginner
instantiations is beginner?!
this channel goes under the assumptions you know about the basics.
what you're asking is very beginner yes..
..I asked where you do instantiation and you wrote the name of the object lol
right
i thought the question was "what are you instantiating
im doing the instancing in a persistent gameobject
already understand the setup, I just saying its not a good way because you're relying too much on Unity events
this is why I mentioned Instantiate returns an object and it would be wiser to use that appropriately
though i wonder even if subscribing to Awake would it miss the ChangeActiveScene event..
i tried var before, it kept giving me compile errors
what? no way var would throw compile error
cause it goes
var InstantiacingObject = Instantiate(CPU.PlayerPawns.PlayerHall);
no?
this would not give a compile error
what was the compile error telling you
mate.. you gotta put methods inside method to call them.
yea you cant use var for a class member 😐
this is why i said #💻┃code-beginner 🥲
what you wrote is nonsense, you don't put methods inside field initializer
I guess we could if we had const functions
... alright
and right now the var variable can be called upon from the outside script?
no?
var was meant to be a local variable
var is just a stand in for the type returned
it puts whatever type your functions returns
public class MyShitMono : MonoBehaviour
{
private GameObject myObject;
void Start()
{
myObject = Instantiate(myPrefab);
}
}
You can do this ^ if you want it to be accesible class wde
then why push for var?!
declare field THEN use it later...
no one pushed for var, it was a quick example to show you that instantiate returns an object..
if its local or class wide, thats up to you..
don't fixate on the var part, it was just used as an example instead of specifying a type
(they are only used in LOCAL variables never in the field declaration)
the important part you need to focus on is how to pass a newly object created to another class
... and Im back to nowhere
not really, you have pretty much an outline of what to do
you are lacking the very basics of c# so it makes it seems harder than it is
alright
InstantiacingObject = Instantiate(CPU.PlayerPawns.PlayerHall);
then do something with InstantiacingObject
because the script that is instantiating all this is persistent
I thought the seperate script just "finding" it would be a straightforward process
It would Find it if by the time it returns the object is in the scene
but Find is shite mtethod
this is still a kick in the gnads
kind useless to show underlin without showing what the actual error is
either way this can still run into the same problem with no finding mainProcess by the time Awake runs
because mainProcess is hasnt been found yet, Im using variable within mainProcess that dont exist yet
no
its beause you're trying to access properties of MasterInterface inside GameObject type
well then if I did just go for the script itself
there is never a reason to use GameObject type , ever
okay so if it returns you a GameObject, and what you're looking for on the GameObject is a component, what do you think you should write there?
at that point you're better of using FindAnyObjectByType
god unity why did you fucking change this 3 times
I am very stuck on this.
whats going on with my output?? none of these correlate to my scripts.
Just unity jank it seems to worsen every version
I get these like 1 in every 15 times I navigate the editor in unity 6
(Not the same error but a similar error)
yeah this has been going on for awhile and i've just been ignoring it but like its getting annoying pfft
is there any like good way to fix it??
Yeah I wish it didn't happen
Haven't really looked it up since it never bothered me so I can't help sadly
thats fine but thank you
Usually with these unity editor UI bugs the first thing to try is to reset the layout
thank you!! i was just about to comment and say i did that and it looks like its working for now
maybe
im just hoping it doesnt come back but it looks good for now
unity shits itself sometimes with layouts :p
third party tabs or maybe too many tabs arraigned weird , stuff like that
texture generation/optimization
its complicated, too long, so i threaded it
related to texture, but its 100% a coding problem
um, would anybody mind helping me with my game's inventory system?
You have to ask specific questions to get help
that's valid. let me arrange my thoughts then
I have an item in my game, and an inventory that stores the item as a list, with it's own class to hold the information about the items.
and an equipment script that has it's own spot for an item of the same class. and a playerstats script that updates the stats when an item is equipped or unequipped. that all work ok I think, I'm really new to using lists and classes like this. My problem is that now I want to add the ability to 'absorb' the equipped item, essentially removing the item from the inventory / equipped slot, but keeping the stats attached to it.
I just really can't find a way to remove the item from the inventory properly.
If your inventory is a list of items (ie, List<Item> Inventory), then there is a remove function that comes with using a list collection.
ahh thank you!
I have this line in my equipment script
public CrystalInventory.Crystal currentEquippedCrystal = null;
this creates a new currently equipped item yes? and then I have it update whenever the player selects a different option in the menu.
is that the right way to do equipment? I'm sorry if my questions seem dumb.
but this means that even if I remove the inventory item from the list, the equipped item will still be there, I could just set it to null?
I should probably have tried following some tutorials before just writing random code that I think might work.
assigning it null just makes that variable not contain anything
it never touches whatever was there
if you want to destroy you have to do it while its in the variable
eg
Destroy(currentEquippedCrystal.gameObject)
currentEquippedCrystal = null
just like
myList.Remove(myThing) removes only the entry
if you want to destroy it and do stuff with it , you have to use that reference while you have it linked
eg
Destroy(myList[index].gameObject);
myList[index] = null; // making the slot empty again although you can just assign new object here
hmm I think I understand. I will try it out
Can somebody tell me if there's an error in my visual debug or if the visual debug isn't the issue? It is supposed to place spheres on the vertices, which it does correctly, but it's also supposed to draw all the edges which it isn't doing.
https://paste.mod.gg/hhxbrsnusvbb/0
A tool for sharing your source code with the world!
Does anyone know why a tilemap over a certain size starts glitching with it's colours?
Ok I have discovered that there is a weird cluster of vertices spheres around the corner of the UI canvas despite there only being one object with this script so that might have to do with it
nvm, the solution is to round the value to smth like nearest 0.05, so that there is a limited number of colours in the world
Everything broke, all the points are clustered around the corner now and won't fix no matter how much I undo the coding changes ahhhhhh I hate working on this so much. I need sleep or I'm gonna attack somebody.
Why would you need that and not an animation event
You can just use the animation event to trigger a function to destroy the item once the animation is over
Isn’t that exactly what you want
Why do you need to specifically use a coroutine
why is my float 0 ???
Because int / int = int
but i explicitly create a float variable
do i need to cast everything to float before?
Only one of them
you assigned the result of a int / int division to a float variable, that's something like converting 0 to 0.0
if you want a float division, one of the elements must a be float
is this really the intended behaviour? it feels so counterintuitive
yes, pretty much all the mainstream programming languages work like that
yes its intendent behaviour, int division give int result, kinda logical, change the division to float point division if you want float point value as a result - one of the input values have to be float point value(or converted in to it)
if you look at operator overloading, its really quite logical in how this works. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/operator-overloading
you have a reference to the first and 2nd value, so an int and int. Theres no concept of "it's later gonna be stored in a float".
yes, it's called integer division
no, definitely not. but most statically typed languages do.
python, and until relatively recently, js, don't, for example
they have dynamic typing though, so you usually don't care too much about types
(python has a separate operator for explicit integer division, //)
anyways yeah most binary operators will give the widest of the operands. int • int -> int, int • long -> long, int • float -> float, double • float -> double
int can automatically be converted to long or float or double through "promotion", no info is lost
but float or long to int would potentially lose info; that has to be explicit
Im looking into making a savegame system, and will only be saving between level states, so only need to save things like story progress settings, research, skills, resources etc. I'm not sure whether to go with system json, newtonsoft.... I may want to serialize dictionaries and polymorphic might be helpful... unsure on the current state of things
just using newtonsoft should be fine. for system.text.json you need to use the nuget package, and im not too sure of any potential downsides there
if you write your save system in a reasonable way, swapping between different json methods should be like a couple of lines difference
thanks, I seem to be reading lots of people saying to avoid using newtonsoft if at all possible, to avoid relying on another library, etc etc.
🤷♂️ ive never seen that advice given ever
was wondering if the alternate systems are actually fully fucntional these days and if netwonsoft is legacy
unity's json is JsonUtility, which has less functionality
STJ cant be used by default, and people have written downsides before i just cant remember them. So the alternative is writing your own, which of course isn't smart to do
Why might relying on another library be a bad thing here?
any serializer will be good, if you dont want to rely on a other libraries you will have to write it yourself, anyway MessagePack is a good and quick serializer but saved data wont be human readable https://github.com/MessagePack-CSharp/MessagePack-CSharp
"Don't take a dependency on Newtonsoft.Json if you don't desperately need it. You might end up in a versionning nightmare."
"If there is a possibility to avoid a 3rd party package, I'll take it any time, using STJ is a no-brainer."
"Why would you use an external package if the framework already provides it.
System.Text.Json. Nobody should choose to do it now, but there is a lot of legacy code that uses Newtonsoft because it was the best choice at the time."
"Newtonsoft only exists for backwards comparability and/or legacy systems these days, afaik."
"Do NOT take a dependency if you don't absolutely need it. The cost of eliminating it later usually is high and there is a cost of maintenance."
Some things i read, not my opinions
From my personal experience with Newtonsoft in both Unity and non-Unity projects, I have never once had a versioning or maintenance issue with it, the most difficulty ive faced is occasionally forgetting the [Ignore] attribute for some types I dont want saved to file, honestly Unitys API would likely change more often than Newtonsoft does, though I can understand in general, wanting to reduce maintaining other packages, plugins, etc on long-term projects
how far down some comment chains did you read to find these 😅
anyways those messages are quite silly. as i wrote above, stj isnt supported by default.
The people saying its a "versionning nightmare" or the "cost of eliminating it later usually is high" probably just wrote shit code
around the top: https://www.reddit.com/r/dotnet/comments/14xgfjl/should_you_use_newtonsoftjson_or_systemtextjson/
though that one is not unity specific i guess
Unity also uses its own package system instead of Nuget, so theres already a lot of 3rd party plugins you cant easily bring into Unity, unless its done through their "Unity Package Manager" (UPM)
surely both of them work just as well as eachother right?
cool, I'll use newtonsoft, thanks 🙂
That's not much of a limitation really, as long as the NuGet packages you want to use (as well as its dependencies) support NS 2.0, which most packages do including STJ.
The main argument of "STJ > NSJ because it's built-in" doesn't really apply to Unity, it's actually the opposite that it's easier to setup NSJ than STJ.
I use STJ in my Unity project because I have more confidence in Microsoft maintaining STJ than NSJ being abandoned with some questionable decisions on top that cannot be removed because of backcompat. But really, either is fine.
Maybe I havnt used all the features of NSJ to encounter any of those "questionable decisions" with it, though it is nice UPM supports NSJ and git repos now, so in this context either would work in Unity, though in general, I dont think all NuGet packages are supported through UPM, AFAIK
yeah this is also some impressions I was getting. I think it's mainly concerns about no polymorophic, and any other missing features that may make my life easier. (I'm a tech artist making a game and haven't done save system logic etc. before so don't really know what I'm doing here so easy is king)
You don't need UPM to install NuGet packages, you can just drag the dlls (as well as dlls of the dependencies) into Assets and that's it, there's also the NuGet for Unity which automates this process for you.
But yeah, possible to do =/= easy to do, NSJ is still easier to setup in Unity than STJ.
You might also want to consider that NSJ has a lot more resources online like tutorials because it's older and gold standard for so long, whereas STJ is relatively new.
yeah, it's a good point and was also considering.... THanks
I'm using this parallax script:
using UnityEngine;
public class Parallax : MonoBehaviour
{
private float length, startpos;
public GameObject cam;
public float parallaxEffect;
void Start()
{
startpos = transform.position.x;
length = GetComponent<SpriteRenderer>().bounds.size.x;
}
void FixedUpdate()
{
float temp = (cam.transform.position.x * (1 - parallaxEffect));
float dist = (cam.transform.position.x * parallaxEffect);
transform.position = new Vector3(startpos + dist, transform.position.y, transform.position.z);
if (temp > startpos + length)
startpos += length;
else if (temp < startpos - length)
startpos -= length;
}
}
And when I start the game it makes all 3 backgrounds snap into the same position, what are the possible fixes? the images are the before and after I start the game
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Also, try to keep your question to 1 channel, its less confusing providing help that way
jordan didnt want me in general so had to come here but yea mb
you also posted in #💻┃code-beginner. cross posting is discouraged here. despite both of these being code channels you're still expected to only use one.
Hey all, looking to create a script that duplicates an existing rule tile and swaps out the sprites in it for sprites in another sheet. I believe I could use CreateInstance to duplicate the rule tile right? But how would I save it as a new file in the editor?
AssetDatabase.CreateAsset will save an asset to disk as a new asset
I need a bit of insight, but what would cause the following statement to create a Null Ref Error:
if (EventSystem.current.currentSelectedGameObject.TryGetComponent<Button>(out Button _button){... }
Would this not just return as false if the currently selected object is not found?
It causes an error when I click off my buttons in my test UI, so I assume that EventSystem.current.currentSelectedGameObject would become a null, but I have also tested
if (EventSystem.current.currentSelectedGameObject == null) { ... }
but that also returns as null.
Would anyone have a clues as to what could cause the Null ref error?
Would this not just return as false if the currently selected object is not found?
that's what theTryGetComponentwould do; but that's not the only thing in that line
but that also returns as null.
what do you mean by this?
You should add debug logs or attach the debugger and see which value specifically is null. Almost all null errors are the same
I found the solution.
EventSystem.current.currentSelectedGameObject.TryGetComponent<Button>(out Button _button)) {
// Your code here
}```
``EventSystem.current.currentSelectedGameObject is null``, and then when I am trying to call a method ``(TryGetComponent) ``on null, which causes the null reference exception.
I had to first check if ``EventSystem.current.currentSelectedGameObject`` is NOT null before attempting to use it
I'd split up that if statement and do a guard clause.
Return if it is null (or whatever similar logic you need to do)
Then do your if statement with the TryGetComponent
It's much easier to follow and that one line isnt so long anymore
Also stuff like this (null errors) is better suited for #💻┃code-beginner
Im fine with Null ref errors. I was more worried that it was something to do with the selection system that is within the UnityEngine's event system.
i am using CineMaschine for a little 3d World of mine. I have a Boss which i would like to put on "look at". But if the Camera is between the player and the boss the player isnt visible anymore. So i thought i could tell the camera to be the furthest away from the Boss as possible. But i dont really know if its possible and how to start
or if there is an better alternative
If you want two different objects to be visible you can use a Target Group
whats that
Operations in C# result in the same type, including operations like division
When one of the two parts become a float, the operation favours floating type for the result
I agree it's weird considering we have methods to determine what to do with the remainder, but I also think it's more consistent.
i need help figuring out how i can go about creating a system where
when you click on the side of two objects where they meet it will join them together and will create a small ball where you clicked and when you remove said ball it will disconnect them and while they are connected you can add more connection balls by clicking on different points along the points where they meet and then you can connect that back to other objects that you have done this to to kind of weld them together and i cant figure out for the life of me how to do it because my first thought was to use parenting but if you tried to attach two points on two seperate objects together the root of the 2nd object might not be the part wanting to be attached to the 1st object and would cause the parenting to get weird and messed up
This might be very silly, but can I convert a Dictionary to a ReadOnlyDictionary without creating a new one?
I want a dictionary that is assignable from within a class, but readonly from outside of it
Iterate over the dictionary and make a ReadOnly out of that
and it'd be a waste to create a new object every time it's accessed
but I don't want to create/update the other object every time I make a change to the base dictionary
that's wasteful
a lot of allocations
public ReadOnlyDictionary<IConfigurationManager.GameMechanic, bool> EnabledGameMechanics => (ReadOnlyDictionary<IConfigurationManager.GameMechanic, bool>)(IDictionary<IConfigurationManager.GameMechanic, bool>)enabledGameMechanics;
``` what do we think about this monstrosity?
I'd really want to avoid a new allocation every time the dictionary is changed
so a conversion would be ideal for me
Maybe make some dictionary wrapper that has both the dictionary and readonly variation
but this looks just terrible
you could just make the type of the property IReadOnlyDictionary maybe?
but then I can't... change it
a wait I missed the I
sounds like you want a nested class with private Set (or Put or whatever, don't remember) methods
(unless there's a better way idk)
yeah, Dictionary implements IReadOnlyDictionary so you can store a dictionary but only allow readonly access by the property
no I don't. Private set doesn't particularly do anything on IEnumerables
yeah that sounds better
not sure what you mean by that
You can present the dictionary publicly as an IReadOnlyDictionary
im not talking about properties
and then internally store it as an IDictionary (or just a Dictionary)
you can edit a dictionary with a private set as easily as you can edit one with a public set, you just can't dereference it by assigning a new one
i don't mean properties
public IReadOnlyDictionary<int, string> Data => data;
private Dictionary<int, string> data;
yeah I think this is the way
note that ReadOnlyDictionary is a weird thing from System.Collections.ObjectModel
Oh yeah that looks neat
it is a class
I assume modifying the dictionary works fine too
you want IReadOnlyDictionary
yeah just noticed
thanks
class CanWrite {
public class PrivateWriteDict : IReadOnlyDictionary {
private void Set(K, V) {}
public V Get(K) {}
}
}
```i mean something like this
(but yeah what fen/simon mention seems easier)
No cast is needed, since a type can implicitly convert to any interface type that it implements
Of course, someone could downcast that back to a dictionary
but someone could also just do evil reflection bullshit too
this is about signalling intent, not enforcing some kind of security boundary
Reminds me to actually start making a lot of my data structs to IReadOnly for my scriptable objects
the other caveat is that if you get a reference to it as IReadOnlyDictionary the values in there can still change, it sounds obvious but you still have to watch out for stuff like concurrent modification errors
it's read only for you!
a nice thing in more recent unity versions is you can expose arrays as ReadOnlySpan rather than IReadOnlyList, it can make iteration more efficient for example
oh noicee
ref struct detected
yes it doesn't play nicely with async methods or coroutines 😛
no heap for you
If I understand your issue correctly, and these objects have colliders, you could try using the closest point on the objects bounds: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Collider.ClosestPointOnBounds.html or access the bounds directly to do the math yourself: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Collider-bounds.html, otherwise if they dont have colliders, you could also get the bounds through the mesh renderer, however the bounds would only give you a cube-like shape that encapsulates the whole space of the object, so if its a rounded object or irregularly shaped object it may not account for that kind of accuracy - if you need that, you could maybe calculate it using a mesh collider or the meshes verts and surface normal from the mesh filter (which may be a more resource-intense approach if your meshes have many verts)
as far as i quickly saw, arrays are more suited if you have a fixed size, and lists for dynamic resizing. is this correct ?
whats the overhead of using a List over an Array ? since the List uses an array internally
yes
the overhead happens when it just needs to create a new array if the size spilled over
so this means reallocating memory
Yes
it creates array twice the size iirc
You can also set an initial capacity if you know your maximum number of elements
That way you pay the allocation cost upfront but not the capacity increases (depending on what you need to optimize for)
okay thanks
i confirm that
VS Code just auto-completed this after I had merely typed OnDrawGizmos() lmao
at u running the latest update?
I have no idea, I just thought it was a funny outcome
My guess is some AI-powered intellisense/autocompletion thing during a weird moment.
It do be having its own innovative ideas from time to time haha
What would an inventory system be classified as? Intermediate or advanced? Cause god damn, I'm ready to smack my head off my desk dealing with this lol
inventories go from all ranges
not all inventories are the same , therefore this is a open ended qustion
Well, lets make it more specific, something to the level of stardew valley
Pickup, split, drag drop, use etc
yes thats more intermediate imo
complex to me is something like Path of Exile and such
mmorpgs / arpgs usually have the complex inventories
I can't for the life of me figure out how to get my inventory to not put items in the slot right next to the original stack when that stacks full, pushing other items down slots
It's annoying, and I'm getting angry lol
i think you're starting too complex too early
start with a simpler inventory of the same type youre going for but then you can put all the small pieces together
I think the problem is not necessarily the complexity, but that how I'm trying to do it doesn't seem to work. Logical thinking lead me to believe "Select slot, check slot has item, if item, add item, if full stack, make new stack, repeat"
But that doesn't seem to eb how its working lol
I could make a whole inventory system in LUA in like 45 mins, but C# is just kicking me in the balls
I've gotten everything setup as far as pickup, and storing the information in lists, updating the UI, just can't seem to sort out how to stop it from adding new stacks of similar items next to one another.
not much can be helped from this end without showing some of the setup / code
normally my slot item has a property IsStackable and StackLimit
Oh, I'm doing that differently, my maxStackSize is implemented in the items itemData itself.
thats fine
as long as you can access it, doesnt matter where it is usually
Kinda hard to share when its spread across 4 files.
But the bulk of my issue is in the following
whoever posted the picture of that game object with a scale of 100,100,100, you really should alter the scale factor of the mesh
setting an object to such a large scale, because the model happens to be very tiny when imported, is never a good idea
set its scale to 100 in the import settings
that formatting hurts lol
surely its not like that in an IDE
well, hopefully not 
Why? what's wrong with it
the first part is indented, yet the rest isnt
I put it in my IDE and it autoformatted
Yeah looks fine in my IDE
next time share code via Site !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
bleh, okay
hard to read big code on discord
huh, I wonder how the file you posted destroyed the indents
No clue, discord does dumb things
I think the only other relative code ineeded for that is this
{
if (icon == null || countText == null || itemNameText == null)
{
Debug.LogError("InventorySlot UI elements are not assigned!", this);
return;
}
// Update the slot UI
icon.sprite = itemData.icon;
countText.text = stackSize > 1 ? stackSize.ToString() : "";
itemNameText.text = itemData.displayName;
gameObject.SetActive(true); // Ensure slot is visible
// Re-enable UI elements to refresh
icon.enabled = false;
icon.enabled = true;
countText.enabled = false;
countText.enabled = true;
itemNameText.enabled = false;
itemNameText.enabled = true;
// Set current item data
CurrentItem = itemData;
CurrentStackSize = stackSize;
Debug.Log($"Slot Updated: {itemNameText.text} | Count: {countText.text}");
}
public void ClearSlot()
{
icon.sprite = null;
countText.text = "";
itemNameText.text = "";
CurrentItem = null; // Clear the current item reference
CurrentStackSize = 0; // Reset stack size
gameObject.SetActive(false); // Hide empty slots
}```
for what its worth, if you saved the file as text.cs then uploading the file will automatically format it correctly to show the coloured text
I ran into an issue where it'd just completely destroy my UI, so I had to hardcode refresh
didn't know that it auto formatted and posted them like that
Interesting. Good information to know for the future
I've never used mobile =p
funny how much mobile differs to the desktop
but other people who are helping might ?
I dont wanna listen to the 70+ discord servers pinging me on my phone lol
they only recently added a way for mobile to play uploaded audio files
the whole point of using those link sites
so people can better read your code
so they can better assits, if its a hasstle, no one is gonna bother
fair enough point
I'm small minded for thinking most people use desktop versions of discord over mobile
But I've also been using discord since before mobile was really prevalent.
God, I've been on discord for almost 10 years now lol
well people do other activities than sitting at PC for whole day, but the phone is still in the pocket
I'm the opposite, my phones typically not with me.
so still can reach for it and help
I'd rather throw my phone on charger or a shelf and go do my business, if I'm at my computer, my phone sits on my desk
Probably one of the smaller margin of millennials that don't have themselves glued to phones in some sense
But I also have 4 kids, so I don't really get the luxary of using my phone
anyone know how I'd move my Physics.OverlapBox relative to my players rotation?
so when I move it along the Z axis it moves along the players Z rather than the worlds Z
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
thank you
can i expose to inspector a list of a scriptable object/class, and make each entry already "instanced" ? like if it was a struct
public List<MyClass> items = new List<MyClass>
{
new MyClass("Default1", 1),
new MyClass("Default2", 2)
};```
Unity objects are always serialized as a reference
The object isn't contained directly
But for plain-old classes or structs, yes
i meant in a editor-only way
yes- what ?
I'm a little unclear what you're looking for now
nav showed an example of a field with an initializer that gives it two items by default
any new instance of the component you put that in will have those two objects stored in the list
that does mean that you're going to create that list every time the class is created (including when unity creates it and then immediately replaces its contents)
Maybe you're looking for the Reset method? That lets you run code when a component is added or reset via the inspector
are you familair with unreal ?
im looking for something similar to the Instanced prop meta, or InstancedStructs
basically the editor instances a object of the type you choose, and will show you all the exposed props
it will serialize with the container
serializing in the inspector already instances the objects
im kinda confused what ur asking now lol
a bit like nav example, but with just new MyClass()
then just give the default values in the field initializer of MyClass
provided the type is serializable, that is already how it works
the issue is that i need to hardcode it in code, a more designer friendly way would be nice
i guess structs are what i have in this case
a friendly way would probably be creating some fields in the inspector to then pass to the constructor
that wouldnt work fine if i wanted a list of unkown size
why not?
what have you actually tried and what exactly isn't working with what you've tried? because everything you've described that you want so far is pretty much how it already works
the editor window can be the one that setups the values for the new() List
because this means i have to manual write all props needed to init a new instances X the count i need ?
Idk what the usecase is exactly so not sure what to suggest.. but there are ways to mitigate that with default values no?
whats "manual write all props " mean here
idk what i previously tried but now it works
sorry for the inconvenience
i guess scriptable objects are a bit special for the serialization system
like Fen already pointed out, UnityEngine.Object derived objects are all serialized as a reference to the object rather than serialized in place like plain classes/structs. this is why when you create a serialized field of some UnityEngine.Object type you'll see a slot to drag one in
hey if i need help with smth is this the right channel to go to
having a really stupid problem where a knockback force works when positive but not when negative
and chatgpt is running in circles
well if a knockback force is negative wouldn't it go in the opposite direction
thats what im saying
unless you are overriding it with velocity
for context im tryna make a little platform fighter for ffun and player one is always on the left and player two is always on the right. their code is basically identical besides variable names and stuff but obviously to knockback player 1 it needs to be negative
thats what i was thinking but its not being overriden because when i make it positive it works, it just pushes him forward instead
its not a hitbox prooblem either i brought the player forward on the z axis so there shouldnt be any collision
obviously to knockback player 1 it needs to be negative
no?
yes because i want to push him left
they cant jump over each other im making this very simple
ok, so apply a positive force in the direction you want
nothing needs to be negative there
thats what i did:
new Vector2(direction * force, rb.velocity.y)
and direction is either -1 or 1 depending on what player you are
ok, how are you using that vector
ill cvopy paste it rq one sec
see !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
nah its one line
ok use single backticks instead to get inline code formatting
float direction = isPlayerOne ? -1f : 1f;
playerRb.AddForce(new Vector2(direction * force, 0), ForceMode2D.Impulse);
mb two lines
i dont think the backticks woorked lol
backticks before and after
oops sorry
you could make this more readable by using Vector2.left or Vector2.right instead
i mean i guess but would that change anything
not really, but it'd make mistakes less likely
what's the issue though?
kinda missed that
basically whenever the direction is positive it works but when its negative it just doesnt its very strange
like ive tested positive forces on both players and negative on both, positive always works and negative never dooes
youre so right sorry
theres like 0 movement at all
no matter how much i juice up the force by like theres NO knockback whatsoever
ive been at this for hours i have never seen a more stupid issue
One of two problems possibility:
- your other code is interfering with this
- you're not modifying the force amount in the right place
Share the full script
but it works when the numbers positive with no interference
Show the code
I could easily write code that behaves that was
the scripts like 550 lines long should i just send the method
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oh fr
Use a paste site ^
ok i use two scripts for this ones the general combat script and ones the movement so ill just send both
keep in mind i realized a way more efficient way to do it when i was already almost through so it might be a bit inefficient
use the links as it was pointed out
the knockback part i showed is at the bottom of the player combat script
i did and when i copied it it gave me that
you paste code on the site, hit save and sent the generated link..
https://paste.mod.gg/aaqjmqlsvovp/0
im sorry never done that beforoe
A tool for sharing your source code with the world!
all good
Your code is doing this every frame:
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);```
so any forces you add will essentially be overwritten entirely by this
noice
so nothings being overwritten
it is tho
dont forget the conditions: thtas being done
if (!isDashing && !playerCombat.p1IsKnockedBack)
so not EVERY frame
this structure with p1IsKnockedBack and p2IsKnockedBack is weird. Why do that with two separate variables instead of just making that a field on the player movement script itself
i mean if it works with a positive direction then im getting the right bool
the fact you've presumably got two separate scripts that do the same thing for the two different players is also kinda 😵💫
bro yeah ngl i made this project a long time ago but gave up on it and revisited it and it was already structured like that so i kinda js kept it
why toeballs
but yeah horrible way to do it
hey hey lets stop judging my horrible style and get to the bottom of the issue
by the way are you modifying knockbackForce in the inspector? or just in the script?
i was playing around with it in the editor to ffind a number i liked
like the most confusing part is that the code is fully functional when direction = 1 but dooesnt work when direction = -1 thats why im saying like it cnat be an overwriting issue
yes but in the inspector or in the code?
inspector
ok good
140 kinda high i dont remmebr if thats what it says in the code but im pretty sure lol
The wother weird thing I'm seeing is...
in the LandsHit method you do AddForce
then it does StartCoroutine(StunPlayer(false, stunDuration));
And inside there you do:
StartCoroutine(ApplyKnockback(player1, knockbackForce, 0.25f, true));
which again does the AddForce
Why are we adding force twice
And maybe you mixed up your directions in that chain somewhere
which could mean that one of the force directions is getting canceled out when you add the second force
i dont understand wheres the second time
StartCoroutine(ApplyKnockback(player1, knockbackForce, 0.25f, true));
Actually yeah that's definitely it
YOu're adding force on line 338 and line 360
in your link
and both of those are to the right no matter what
so if you then add a left force in the other place, it cancels out to 0
if you add a right force it doubles
you probably want to just delete the AddForce on line 338 and 360
inside p2ExecuteAttack and p1ExecuteAttack
YOOOOOOOOO WAIAT
i love you guys
thank you so much
silly ahh mistake but much appreicated everyone!!!!!
hi guys im new to unity and unity networking with netcode
im trying to displat info about an annotation object (prefab) when is hovered
is working for host, but not for client ( is just an empty string)
void Start()
{
if (!IsOwner) return;
_camera = GameObject.FindGameObjectWithTag("PlayerCamera").GetComponent<Camera>();
}
void Update()
{
if (!IsOwner || _camera == null) return; /
Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(ray.origin, ray.direction * 100, Color.red);
if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, _layerMask))
{
AnnotationComponent annotationComponent = hit.collider.GetComponent<AnnotationComponent>();
if (annotationComponent != null)
{
RequestAnnotationInfoServerRpc(annotationComponent.NetworkObject);
}
else
{
HideAnnotationClientRpc();
}
}
else
{
HideAnnotationClientRpc();
}
}
[ServerRpc]
private void RequestAnnotationInfoServerRpc(NetworkObjectReference annotationObject)
{
if (annotationObject.TryGet(out NetworkObject annotationNetworkObject))
{
AnnotationComponent annotationComponent = annotationNetworkObject.GetComponent<AnnotationComponent>();
if (annotationComponent != null)
{
string info = annotationComponent.Data.Value.info;
Debug.Log($"Sending annotation info: {info}");
// Send the annotation data to the client
DisplayInfoClientRpc(info, true);
}
}
}
[ClientRpc]
private void DisplayInfoClientRpc(string info, bool showInfo)
{
if (showInfo && !string.IsNullOrEmpty(info))
{
Debug.Log($"Received annotation info: {info}");
_annotationInfo.text = info;
_annotationCanvasInfo.SetActive(true);
}
else
{
_annotationCanvasInfo.SetActive(false);
}
}
[ClientRpc]
private void HideAnnotationClientRpc()
{
_annotationCanvasInfo.SetActive(false);
}
i dont know whats wong
any advice is welcome
oh thank
how does the unity library ecosystem work?
What would I need to do for my library to make it so that unity developers can use it?
so far i support dotnet6/7/8 and publish to nuget but i see conflicting information online about whether or not that is enough
I smell a "massive dialect system" 😔
what do you mean by that?
you mean Unity as plugin ?
the way the netcode is written has a general LLM feel
what is a plugin?
i have zero experience with unity
oh nvm. You want to make like what nuget packages for unity or .unitypackages?
I dont envy the task debugging gpt netcode 😅
oh like this one ? ah yeah maybe
i guess nuget packages for unity
for some more context im working on an ecs/ec
and want it to be able to be used in unity
as long as it targets .NET 4.x or <= Standard 2.0
dotnet 4 😭
wild
yeah sadly
6, 10, or 20 piece?
hopefully unity 7 brings in the new "Core" CLR
with a side of biscuit
by .NET 4 you mean any dotnet framework 4.x right?
correct
ok at least its something in support xD
Its mainly the speed , most other things are syntactic sugar
.net 4 is painfully slow compared to .net 9
iirc some stuff is omitted but you can put the dlls back
unity just picks and choose specific dlls
had to do the same for other things that normally are available in 4
mm
i see
sometimes you also have to switch it from standard 2.0 to 4.x for dll to work
polyfill time
Probably better in #archived-shaders
Really? Compute shaders aren't really just shaders... They're some bizarre middle ground. But if you say so.
they are shaders - it's right there in the name!
and when you consider that the programming paradigms and languages involved are exactly the same as regular shaders, it makes a lot of sense to ask those people.
Compute shaders, for all intents and purposes, are just HLSL. It's only the context of materials that makes the term "shader" seem like it's specific to those
If i subscribe functions using a lambda expression how do I get them to unsubscribe if I don't even have the function identifier?
Or should I just not use lambda expressions in this case then
You would have to save the lambda to a variable
It's really usually best just not to use a lambda here instead
Thanks!
Just dont use lambdas to subscribe to events. To me at least thats code smell.
Unless it is a one shot type of event that can do it’s own cleanup like a OnComplete
This all really depends on lifetime of the producer object. If you don't need to unsubscribe before the producer object's lifetime is over it is generally fine. But I could also see the benefit of never doing it as a code style.
Producer objects will keep their subscribers from being garbage collected but the same is not true for the reverse case.
This is why static events are extra dangerous, not unsubscribing from them can lead to memory leaks and undesired behavior.
Why must my derived class have a constructor with parameters if the base class does not have a parameterless constructor?
the problem is solved by implementing a constructor that has parameters which is very weird to me
Because it has to follow the contract set by the base class
You can get around this by setting the constructor in the base class to a private parameterless constructor and using static factory creation methods instead
In your current implementation without the parameterless constructor, the derived class can't follow the contract of the base class without that parameterless constructor because the only way to fulfill the contract of creation is to pass parameters to the only constructor that has parameters.
What if my derived class doesn't need to override the base constructor and just have it call the base constructor anyways?
Does this mean that the "contract" is now the parameter'ed constructor like here?
constructors aren't inherited, so yeah you need to explicitly tell your derived class how to create the part of itself which comes from the base class, even if it's not adding anything new
Thanks!
Does anybody know where I can find the radius float with a cinemachine camera? I've been trying to search within the class but I cannot find anything within its structs. Also, if anyone knows a way to find a specific variable within a script and all its structs/classes i'd be so thankful
Nevermind, it's not in the cinemachine camera class, it's in the cinemachine orbital follow
If you have to use events, I would have a method specifically for the event, then you can specifically subscribe and unsubscribe that method. You don't have to store a local func variable.
Events take a method reference
You subscribe with one, you unsubscribe with one
Anonymous lambdas don't have a reference stored so if you use the same one in the unsubscribe call it will be a new reference, not the same one. That doesn't work.
Are you directing that to me or to someone else?
As a general remark not aimed at anybody in specific
Same thing as when you compare classes, the default behaviour is by reference. Methods work the exact same way. Delegates are essentially variables like classes would be.
Yep
Hello, I want to make a system with seeds to handle anything that's random in my game, but I have no idea how to go about it. Any insight/resources?
You just initialize your random number generator with the seed
Youi could use Unity.Random or System.Random as two simple examples
initialize it with your seed
then generate the random stuff as normal
That's really useful i didn't know that was a thing thanks a lot
Can I "chain" a coroutine so that it can be invoked at any time, but it will run the moment the gameobject is enabled?
start it in Start()
or OnEnable
starting it is in a function that's listening to an event
but then it will run every time the object is enabled, not only when it's chained
what does chained mean
I have a general question about a function that I can't figure out how it works, and the documentation and stuff online doesn't make much sense. Would I ask here?
depends. what's the function
I mean it waits until the object is enabled rather than trying (and failing) to run immediately when I get the event callback
use a bool
Addlistener
I suppose
it makes zero sense.
how does it make zero sense?
you mean like for events? (also yeah #archived-code-general )
I need to add an onclick event to a button when instantiated. It might be that I can use this, but I have no idea. There is not much documentation at all about onclick events, it seems that they are mostly just part of the inspector view and not the actual thing happening
just realised this isn't #💻┃unity-talk, 
you probably just need to look specifically for events and not onclick
what do you mean? you get the reference to a button, then you do
button.onClick.AddListener(MyListenerFunction);
want me to post the code that needs to do this?
I mean sure, but if it's long then use one of the code posting websites
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
public void CopyTask(string newTaskData)
{
//do not fix or TOUCH AT ALL if this is touched everything breaks!!!
//do not optomise in fear of project collapse
Debug.Log(transformYValue);
transformYValue = transformCount * -150; //makes distance farther for every new task
GameObject newButton = Instantiate(buttonPrefab, new Vector3(0,0,0), Quaternion.identity, buttonParent.transform);//creates new button
newButton.gameObject.GetComponent<buttonStringKeeper>().buttonString = newTaskData;
transformCount ++; //increases distance for next
}
not my first time
its two seperate voids
I'm not sure I understand, is this the function that needs to be called in onclick?
the second one that the button needs to call is:
public void OpenOverlay1FromInspector()
{
GameObject clickedTask = GameObject.FindWithTag("TaskClicked");
string messageAndPoints = clickedTask.gameObject.GetComponent<buttonStringKeeper>().buttonString;
//^^^finds task that was clicked and takes it's string
string[] splitData = messageAndPoints.Split('|');
string message = splitData[0];
int points = int.Parse(splitData[1]);
string link = splitData[2]; //should set 3rd split value to link
OpenOverlay1(message, points, link);
clickedTask.gameObject.tag = "Untagged";//untagges tag
}
the current way is adding a tag when it's clicked and then using that to find the script component with the variable and then removing the tag
just to check, do you know what events are?
not really. I'm not well versed in this
try watching this video
🌍 FREE C# Beginner Complete Course! https://www.youtube.com/watch?v=pReR6Z9rK-o
🔴 Watch my Complete FREE Game Dev Course! 🌍 https://www.youtube.com/watch?v=AmGSEH7QcDg
📝 C# Basics to Advanced Playlist https://www.youtube.com/playlist?list=PLzDRvYVwl53t2GGC4rV_AmH7vSvSqjVmz
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn...
sorry I'll have to ask later I gotta run, in between classes now.
newButton.GetComponent<Button>().onClick.AddListener(OpenOverlay1FromInspector)
although do watch the video that not jordan sent
understanding why this is the solution, will be helpful
just for the quick run-down though. events are basically just a list of functions that can all be called at once.
UnityEvents (which buttons use) are serializable events, so you can subscribe functions to them in the inspector (might need someone to fact check that, just going off of my personal experience with them)
why's that? understanding basic c# seems a lot more helpful than understanding a single branch of it
CodeMonkeys tutorials generally arent that good, and im sure you could see that if you look closer at the video you linked
I said that they should watch the video, wdym
i have looked closer. that's how i learned about events...
oh mb, misread. sorry, bit tired
you really dont need to use EventHandler in unity
true, although its only really for the sake of the tutorial. if you were learning basic c# then that is what you would use. in unity though its simplified by UnityEvents
what, no. you just simply dont need EventHandler. its not "simplified" by UnityEvent
CodeMonkey's tutorials have generally been known to not be so good. If you wanna learn c# events just follow a basic tutorial that isnt unity specific
yes, in c# its useful, in unity its not. which is mentioned in the video
my comment was specific to the point of "in unity though its simplified by UnityEvents"
i dont really see what exactly you're confused by there. i honestly haven't looked into the UnityEvents docs that thoroughly but from experience thats just how they've worked
im not confused by anything? Im saying CodeMonkey's tutorials and specifically that one you linked is not good lol
❓
code monkeys tutorials have been fine to learn from for me. bit complicated and long but they're not that bad.
jordan is talking about C# events vs. UnityEvent
yes and i am saying their claim is wrong that "in unity though its simplified by UnityEvents"
Nothing here is simplified by UnityEvent. You don't use UnityEvent as a replacement for EventHandler, 1 because you dont need EventHandler at all to use c# events in unity. and 2 because the purpose of UnityEvent is to make it show in inspector
yes, in c# its useful, in unity its not.
considering we're in a unity context, why does he use it throughout the entire video?
its basic c#
which y'know, is the title of the video.
i think EventHandler (the Unity UI component) has gotten mixed up with C# events
if you're trying to claim his video isnt specific to unity, please scroll through any of the video and look at the actual code
i mean you can learn animation in blender. doesn't mean you can only use that knowledge in blender. same goes for c#, most of this stuff is transferable to other software
I don't understand what your point is
i think they just dont like code monkey, which is fair enough i guess. there's other tutorials out there.
its not about if I like them or not. ive written it twice above, the quality of their tutorials is just not that good
So, I have a lot of line renderers. Displaying a bunch of data all at once, and I need to know when a specific line is clicked on. Way too many for even a Capsule Collider to run decently well on. I have the lines generate their capsule on start, and they never move, but they're still nuking my framerate when they're on screen.
Is there a way I can either:
- Make a capsule collider significantly more lightweight
- Detect when I click on a line renderer using pure math at time of click rather than keeping a collider around
i mean all the tutorials online have some issue with them. so long as it works it seems fine to me
How many is a lot, how long are they?
Let me get a count of the lines real quick. As for length, it's about 10-20 units long on average
Ballpark, I'm guessing about a thousand, but I can get an accurate count in a bit
Job system time
i would expect you can have a couple thousand if you don't have them all bunched up, which would mess up your broadphase
They're pretty bunched actually
i have a scene with ~10k static box colliders all inter-colliding, but none of their AABB overlapping, that causes no performance issues at all
Maybe I should try box colliders instead of capsule? Would that make a huge difference?
you could render them to a 16 bit render texture with each line having a different color, then check the pixel on that render texture you are clicking on, assuming you want the topmost one, that would be quite easy to make
i was going to suggest that initially but assumed you're using capsule for a reason. if they have some decent width to it, the edges of the box might be annoying
probably no significant difference
i would expect your issue to be primarily that the BVH of the physics system will have to check too many colliders in its narrow phase
If I put them on a layer that could not collide with itself, would that help at all?
Are they completely arbitrary? Is there any kind of rhyme or reason, mathematical or otherwise determining where they are?
how are they created/generated?
They're being generated after parsing a file, they're representations of data
we might be able to build up some kind of queryable data structure from that same data
though I guess we'd be hard pressed to make something more performant than PhysX's system?
Is this 2D or 3D?
something like a network graph and you want to be able to click on the connections?
Or rather, 2D or 3D plane
3D, non-planar
Essentially, I have a bunch of data about where a gunshot could happen and data about how much damage it might do and to what, and I'm trying to draw a line for each one, and let someone click on it to get that additional info
Some big fancy math program computes "Someone standing at this location and firing at this angle at some building or vehicle with this caliber has a XX% chance of injuring someone on the other side" and stores it in a file, I'm parsing it and showing those lines for people to get a visual idea of what the numbers mean. If someone wanted to be incredibly thorough, they could simulate essentially a sphere down to individual degree resolution for multiple types of weapons, which would generate a lot of data. I'd like to at least somewhat try to display that data
map line to pixel on screen, look up which line is the topmost one in that pixel.
Yeah, that seems the most feasible, I'm just working on implementing it
you would probably need some sort of compute shader so you don't have to CPU-query the texture
Okay, so, rough approximation:
On mouse click, rasterize images to render texture
Do some sort of magic shader thing to mask out everything but the lines and then give each line a unique color identity
Get screen coordinates of mouse, convert to coordinates of render texture
Query pixel at that location, look up which line has that color identity
Execute "clicked on" functionality of that line
yes, big question would be how to avoid the downloading of the render texture, i.e. making a copy of it in RAM. Maybe you can actually copy just one pixel. https://docs.unity3d.com/ScriptReference/Graphics.CopyTexture.html
I had to do something kind of similar when trying to save a normal map from a runtime-loaded mesh as an asset in the project with an editor script, it'd be something like this, but I'd need a new shader that does this "no graphics, lines only, final destination" thing?
Texture2D dest = new Texture2D(baseMap.width, baseMap.height);
RenderTexture renderTexture = RenderTexture.GetTemporary(baseMap.width, baseMap.height);
if (isNormal)
{
Material blitMaterial = new Material(Shader.Find("Hidden/DXTnmToRGB"));
Graphics.Blit(baseMap, renderTexture, blitMaterial);
}
Actually you would have to only render the pixel around the pointer, and the shader could be ObjectID in a channel of TextureFormat.RG32
try {
action.Do(this);
} catch(Exception e) {
e.Message = $"Error occurred in state {stateName}.{eventName}.{i}" + e.Message;
throw e;
}
is there any way to do something like this? I would like to be able to see where the error occured so I can more easily figure out what the issue is
idk how ur supposed to do this sort of thing in unity
just look at your stack trace
you can throw any exception you like in that catch, including any message you like
or call a Debug.LogError/LogException in it
I tried that but it doesn't include the proper trace for some reason ill try the debug.log thing
you will have to do a Debug.LogException(e) or throw e if you want the original trace and another Debug.Log("my info") next to it with your added info
if you throw e, is it also actually including the stack trace? not sure if im remembering wrong but i think might only show the message
i think it'd generate a new stacktrace? not sure
try printing out e.StackTrace
it just shows the trace of the throw not where it originally comes from
I tried inner exception because I remembered that working before but then it just displayed the original without the new stuff
I guess it could work but its not ideal by any means
yeah im pretty sure this happens
Debug.LogError($"Error occurred in state {stateName}.{eventName}.{i}" + e.Message + e.StackTrace); this seems to work ok
in the case above, what extra stacktrace are you expecting? its not like you're calling fixedupdate yourself
i normally avoid trycatch, unless these are errors out of my control. stuff like user input or files
i wanted the original stack trace just also with the info about which state and action it occured in
which the above works so im happy
if you didnt have it in a try catch it should just print out all the info normally
in 2022.3, is there a method to make a navmesh agent face a raycast point without moving to it?
you can set the rotation to be whatever you want through the transform
the way it rotates by default is very weird to me
please don't crosspost
you were already instructed how to post code appropriately in #💻┃code-beginner
i used one of the websites
i used the paste mod one
ok, post the link where you asked originally in #💻┃code-beginner then
not to be rude or anthing i was just really confused bc you just typed that command whitout saying anything else
ah yeah the paste sites don't really give instructions
I'm having a problem with knowing how to implement scriptable objects as data containers for gameObject stats.
I get that I can have a ScrOb with Health, color etc, and a gameObject prefab with those same properties. But is there a design convention around how to get that data onto new objects correctly?
Should the prefab have some kind of constructor function that populates its stats from the ScrOb?
Should there be a 3rd script created that is just a maker that instantiates the prefabs?
Should an enemyManager or InventoryManager be filling its own list with a construction script that copies the data onto the prefabs?
I can follow the idea through a tutorial, but I seem to fall apart especially when coding something to handle groups of enemies as the Encounter is a ScrOb that has a list of Enemy ScrObs, but how to spawn that out into the game gets messy.
usually SO is the abbreviation of scriptable object
i wouldnt say there is really a design because its just a matter of copying the data from the SO to your code. You mention a SO with "health, color, etc" and a prefab with those properties, well the GameObject doesnt know anything about health or color. You must already have some script on those prefabs for these values. In that script, you can have a reference to the SO you want it to copy data from. In awake you can copy the data
I feel like I get that part. Like I have an enemy script, and an enemy prefab with that script attached as a component, and an enemy SO where I can design and tune enemy values.
During awake, how does the enemy script get the reference to the enemyA SO that it should populate data from?
When I want to spawn a group of enemy A, vs enemy B, is there any convention as to what should be passing the enemy SO to the enemy script?
Examples I follow feel like they especially break when I get to a SO that has other SOs in it.
During awake, how does the enemy script get the reference to the enemyA SO that it should populate data from?
this is what i described above, your enemy script can have a field for the EnemyDataSO (or whatever name) and just drag it in the inspector.
presumably, enemy A would be its own prefab. Enemy B would be its own. You assign whichever SO you want to each prefab
I have a top down game, im procedurally tilting the character model based on input. but when i rotate the character model to say look left, and then i start moving, it tilts based on its rotation so clicking W which moves you up it would Yaw left instead of pitching down, how do i make it tilt based on world XYZ or even based on the Character Controller rotation which doesnt rotate?
Oh yeah, if it was fully pre-laid out, but these enemies are being chosen at runtime
what changes in this case? you can still have EnemyA and B exist as prefabs and then spawn them whenever you want. A and B during awake just copy values from the SO
I can I suppose, but the documentation for scriptable objects states outright that you can make a more general prefab that is then shaped by the scriptableObject information, so you can have more variants with a much smaller memory and disk size.
If I just made a prefab for every enemy, why use a scriptable object?
when you said enemy A vs enemy B, this seems to me like completely different npcs. you'd probably want to have different prefabs for these different npcs
Now if enemy B is one NPC but can have different health (one spawns with 50, one with 100) then you wouldn't want 2 prefabs for that. The SO could hold all the different stats it can spawn with
part of this is also dependant on your game itself, so its a bit easier to help if you have specific examples you need this for
Okay, lets use a more expressive example. If I had pokemon prefabs. I could make a bulbasaur prefab, and have SOs for a level 5 and a level 30 version. And I could do the same for a charmander prefab and SOs.
But with most of the same properties, couldn't I just have one pokemon prefab, and then SOs that load name, stats, sprite, moves etc?
Either way, I think I understand the difference between those two implementations, but once you walk into an enemy trainer, they have a list of pokemon. A "team" SO, that is a list of pokemon SOs, each of which has a list of 4 moves, also SOs.
I'm more interested in designing the right flow for what mechanism tells the battle screen how many prefabs to load up, how to pass each prefab the SO it needs, and then which script should be responsible for copying the data from the SO onto a given instance.
If I pass each prefab an SO, and it copies data out of the SO, onto itself that's fine, but I think I'm missing some kind of manager that keeps these prefabs wrangled in a list so you can actually target them. And with multiple layers of SO I keep getting errors where parts of a prefab want a finished Move object, not an SO of a move.
I just used chat gpt to make some very specific code that I didn't bother to make by myself
I just needed a script that makes a new render texture and a new material variant for every instance of that object so that they don't interfere with each other
For each pokemon I'd have a single prefab/SO for each such that this SO gives the default/range of stats it can get each level up.
As for passing stuff around, you can always make some like lookup table where you bind these prefabs/SOs, but it's not always needed depending how you're serializing these prefabs. For instance, you have pokemon grouped by zones, so instead of having to access this global lookup table you just look at the current Zone data and grab it from there.
Where can I get help with the problems I experience while developing a game?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
got caught up with work
i dont know if you really wanna use SO like this. you could have one prefab and SO's representing every pokemon but it starts to become really tedious. Yea you'd save a tiny bit of memory but i dont know if this is worth the effort. You'd also have to figure out a way to assign the SO to a prefab. Like when you want to spawn bulbasaur, whichever script is responsible for that needs to look up what the bulbasaur SO is (or have a direct reference to it already).
I think the initial sentence you had was good, a bulbsaur prefab and SO for the stats. The SO could even link to the next evolution (a prefab)
As for the enemy trainer, I think you might be going overboard with the SO's. Maybe. A team SO could just be a list on your monobehaviour on the prefab. Idk if you're ever gonna be reusing teams. A list of pokemon SOs would be avoided if you had a prefab per pokemon (tying into the 1 prefab and many SO discussion). I could see the moves being SOs but again you'll need to find a way to map these. If a pokemon move changes, you'll need to store that in a file. When you read that file, you gotta figure out which SO it corresponds to. Be careful for the moves as an SO too if you ever need to store "state". Like if an attack needs to store information, you shouldn't do this inside an SO because everything referencing this move will be referencing the same instance.
thanks bestie. big help
Same for work 😆 , but I appreciate the perspective. There's some good questions in there to reflect on too, like which encounters could be reused (ex: FF random encounters) or what wouldn't be. Are particular fights static to one off scenarios like bosses.
Just another two cents being thrown into the well. a mix of ScriptableObject's and POCO/base classes could be nice here
a ScriptablePokemon per pokemon to define stuff like display name, element type, pokemon description, sprites etc. and then a poco class of base stats used to roll the real ones when caught (in this screenshot they are standard sliders but you would want cooler minmax ones to decide the values it could be rolling from)
then trainers could be defined as a ScriptableTrainer that uses a TeamPreset like this (the player could use this too)
[System.Serializable]
public class TeamPreset
{
[field: SerializeField] public PokemonWithPreset First { get; private set; }
[field: SerializeField] public PokemonWithPreset Second { get; private set; }
[field: SerializeField] public PokemonWithPreset Third { get; private set; }
[field: SerializeField] public PokemonWithPreset Forth { get; private set; }
[field: SerializeField] public PokemonWithPreset Fifth { get; private set; }
[field: SerializeField] public PokemonWithPreset Sixth { get; private set; }
}
[System.Serializable]
public class PokemonWithPreset
{
[field: SerializeField] public ScriptablePokemon Pokemon { get; private set; }
[field: SerializeField] public PokemonValues Values { get; private set; }
}
Where you use a pairing of the templated pokemon values along with the instance of PokemonValues for dynamic modification. (This looks abit ugly in the inspector by default but some pretty basic editor programming could show them more inline, any general editor extension package likely has options to do this for you too)
Might be a stupid question but im trying to instantiate a Camera from a prefab in DOTS, ecb.Instantiate(camera_prefab) However I can't set the camera to the main camera, the game view remains blank. Even after setting MainCamera in the prefab descriptor and ensuring it's the only camera in the scene.
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
void Update()
{
PlayerRotation = Player.transform.rotation.eulerAngles;
RotationAdjusted = new Vector3(PlayerRotation.x, PlayerRotation.y + 180, PlayerRotation.z);
transform.rotation = Quaternion.Euler(RotationAdjusted);
SurfaceNormals = RotationFSM.FsmVariables.GetFsmVector3("left hand normal").Value;
Debug.Log(SurfaceNormals);
Quaternion TargetRotation = Quaternion.FromToRotation(Vector3.up, SurfaceNormals);
transform.rotation = TargetRotation;
OK so I'm trying to convert some code from playmaker to c#. I thought I did a 1 to 1 conversion but the c# version doesn't seem to work properly.
You might be confused as to why I would set the rotation twice in 1 frame. The reason is I am trying to align a hand to a surface normal but this rotation doesn't take into account the direction the player is facing so my hand would rotate fine in one direction but would be broken by 180 degrees when I turn around.
Setting it like this fixed the problem, somehow.
nvm i found it, i was missing: HYBRID_ENTITIES_CAMERA_CONVERSION
I tried adding:
transform.rotation = Quaternion.Euler(transform.rotation.x, TargetRotation.y, transform.rotation.z);
but it doesn't work either. Not sure what I'm doing wrong, the same thing works in playmaker
this is kinda vague, what doesnt seem to work here?
i would go step by step and check which value is actually different from what you expect it to be. Theres a lot of unknowns here that we cant really see like GetFsmVector3
Ok can I show you the playmaker FSM? It fits in one screen. You may not know how to use playmaker but it might help
i was just pointing out that theres a dots channel for your future dots questions
aight, ill use that in the future, thought this was general enough, as #1062393052863414313 seems to be the more advanced stuff.
ok it didn't quite fit but the last action just aligns the Y axis to the surface normals
I was trying to replicate the same thing in C#
you can show it but again theres a ton of unknowns. also im not sure what GetFsmVector3 does, but if it doesnt use the rotation of the existing object then setting the rotation twice there does nothing
it just gets a Vector3 variable from a playmaker FSM. So, a script
well yes i can see that given how its used and the name...
the question is what math its actually doing to get these values
In that fsm, I raycast to get the surface normals and try to align a hand to them. I use the same variable to do this in a playmaker fsm and it works there, doesn't work here and I don't know why
so if its raycasting and just getting the surface normal, then the first part of your code does nothing. you set the rotation, raycast to get the normal, then you get a rotation that rotates from Vector3.up to the normal, and you set that to be your new rotation
maybe you want to multiply the current rotation instead?
transform.rotation *= TargetRotation;
yea see, that's the thing
also this doesnt make sense, rotation is a quaternion so using it as euler angles doesnt work
in playmaker, that didn't work cause I'd align the hand perfectly in one direction but when I turned around in the opposite direction, my hand would be broken by 180 degrees
doing that double rotation fixed it
i think you should stop focusing on what you did in playmaker because i am pointing out glaring issues for you on why exactly your current method doesnt work
I am just trying to explain why I did double rotation
and i explained why the double rotation you did doesnt actually do anything..
it doesnt matter if you assign it twice, or 100 times, if you are just overwriting it without using previous values in some calculation, it does nothing
again its really hard to visualize what your code does because theres so many unknowns there. Idk if this is what you actually need but maybe just try what i said with the last line. multiply the quaternion, which is like adding the rotation
transform.rotation *= TargetRotation;
with this, you would actually be using the previous rotation in your calculation. its adding the rotation rather than completely overwriting it with an unrelated value
I actually did try that but I got a slightly innacurate result. Let me try again but I'll remove that other code that should be reduntant
Just in case it was over looked, reminder that a quaternion isn't the same as an Euler and should not be used as the value for the Euler method.
also it's getting way to late here, I'll deal with it in the morning
yea i wrote that above somewhere
I try to avoid quaternions because I don't understand them, but I guess it's because you can get away with a lot of stuff (like using only eulers) in playmaker.
I'm still clumsy with c# and I need to improve and pick up better practices
I will improve
Well, you're feeding the values of one into an Euler above in your code
Nevermind.. I may have mislooked
there isnt too much you need to understand about them, i think whats confusing you is how you're using the last rotation. FromToRotation basically gives you a rotation to bring one vector to another. So the rotation to go from Vector3.up to SurfaceNormals
Actually now that I think about it, maybe you want the transform.up where transform is the hand
when it comes to rotation stuff, id add a ton of debug lines to visualize. printing out values doesnt really mean much to me
the secret is to not actually do quaternion math
(there is no reason to do this)
you just use the Quaternion methods to manipulate rotations
Is there a way to store a scriptable object's property immediately to disk without saving the entire project?
are you doing something like changing the value in code? 🤔
in that case make sure you mark the SO as dirty
https://unity.huh.how/editor-extensions/serialisation/persisting-changes
Right but that won't save to disk until the project is saved.
have you actually tried it? because it works for me
Okay thanks!
note that it will not mark the asset as dirty
Hey guys, im having some issues with a line renderer projection
private void LineRendererTrajectory(Vector3 startPosition, Vector3 direction, float totalDistance)
{
LR.positionCount = 2;
LR.SetPosition(0, startPosition);
Vector3 currentDirection = direction.normalized;
int obstacleLayer = LayerMask.GetMask("Obstacle");
Ray ray = new Ray(startPosition, currentDirection);
if (Physics.Raycast(ray, out RaycastHit hit, totalDistance, obstacleLayer))
{
float remainingDistance = totalDistance - Vector3.Distance(startPosition, hit.point);
LR.SetPosition(1, hit.point);
Vector3 reflectedDirection = Vector3.Reflect(currentDirection, hit.normal);
Vector3 finalPoint = hit.point + reflectedDirection * remainingDistance;
LR.positionCount = 3;
LR.SetPosition(2, finalPoint);
}
else
{
Vector3 endPos = startPosition + currentDirection * totalDistance;
LR.SetPosition(1, endPos);
}
}
This is my method here, the issue can be seen in the video
https://streamable.com/tswd71
When the second line reflects back into the original one and 10* within it, the lines shape is kind of weird, and im unable to find a solution on how to make it consistent
So I'm having sorta a hard time figuring out the Inventory system for my game.
I need to have the 3 main slots for every other item besides the Headgear & lighter.
This is the inventory code system, (The last 2 images are from the same script)
First of all, share !code correctly:
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Ok thankyou lemme do that
Just like this?
https://paste.mod.gg/dlqooijrmgyb/0
if so that first file newfile.cs (I'm not sure how to change that name) but it's the InventoryManager.cs
A tool for sharing your source code with the world!
Yes
Awesome thankyou
I am attempting to implement Sabastian Lagues implementation of Poisson disc sampling, but with a few of my own tweaks. For example, making it so points can't generate too close to the center of the region.
Getting to the point, I am currently trying to figure out how to increase the radius when the points are further away from the center of the region. But I am very stuck on how to do so.
This is my adjusted code:
Poisson Disc Sampling: https://hastebin.com/share/iqeracofat.java
Script that runs/debugs the method: https://hastebin.com/share/amokicupak.csharp
Essentially, I want Variable Radii Poisson Disc Sampling, and I currently am using the Bridson Algorithm.
So basically, you need some way to identify the slot types and specify what slot types your items can go in. One simple way to do this is use an enum defining the slot types. And assign a variable of that enum type both to slots and items.
I'll look into thankyou
That question sounds very specific to the mentioned algorithms. I don't think anyone would be able to answer them, unless they're expert in that field or have been dealing with it recently.
Maybe if you can generalize the question to make it less algorithm related, someone could help.
heya, is anyone familiar with the "correct" way to attach clothing to a humanoid rig if they aren't part of the same fbx?
I'm creating them all in the same blender file (just for testing) using the same armature, then I export them separately with the same armature, instantiate the clothing on the humanoid model, and set their bones & rootbones to be equal to the humanoid's skinned mesh.
but then I get results like shown, where it seems to be tracking the torso but not the arms..? I can confirm the arms are weight painted correctly & track the armature in blender https://gyazo.com/4b75cf5f5a135074c1bfbff69fb43fd3
ignore his hat I turned it upside down by accident
and if I apply the bone transfer in editor / not in play mode, it works fine
figured it out, I had a magicacloth component that was breaking when the mesh was having bones swapped (this didn't run in the editor, hence the bug)
Using this, I can't seem to find why my sprite image when I pick up a item isn't loading onto my hotbar?
A tool for sharing your source code with the world!
Would putting [Serializable] on a parent class affect all the derived classes or no?
Also on that note, why is [Serializable] not an option by default? (I currently haven't encountered a case where serializable has not worked)
To answer your first question - no it only affects the class it is used on and not derived classes as well, same is true if you used it on a base class and then inherited that base class, it will not also serialized the class that inherited the base
Your second question im not completely certain on why its not a "default" thing, as [Serializable] is often to allow Unity to draw that class to the inspector, and for serializers like Newtonsoft to save/load its data to file, although Newtonsoft doesnt require that attribute to do this so it likely could be "not everything needs to be serialized all the time", though thats entirely a guess
could you help me with this lock coding?
Lock coding? What do you mean?
im coding a special type of lock where you have to hold the shackle for 2 seconds for it to play an unlocking animation
And whats the problem that your having with that? Also what do you already have so far?
this is my code so far:
using UnityEngine;
public class LockShackle2 : MonoBehaviour
{
private Animator anim;
private void Start()
{
anim = GetComponent<Animator>();
if (anim == null)
{
Debug.LogError("Animator component not found!");
}
}
private void Update()
{
if (anim == null) return;
if (Input.GetMouseButtonDown(0) && isMouseOverObject())
{
anim.SetBool("isPlaying", true);
}
else if (Input.GetMouseButtonUp(0) || !isMouseOverObject())
{
anim.SetBool("isPlaying", false);
}
}
private bool isMouseOverObject()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
return Physics.Raycast(ray, out RaycastHit hit) && hit.collider.gameObject == gameObject;
}
}
for some reason it says the compiling is wrong
wrong one
Thank you!
You can use codeblocks to format that on Discord (3 backticks, followed by the words "cs" then ending with 3 more backticks), easier to read:
```cs
your code...
```
alright
i posted an image of it tho
You should [RequireComponent(typeof(Animator))] instead of all the null checks
mk
where should i place it
Often code is much better than a image, since you can interact with code far easier than you can interact with a image, and sometimes resolutions can make images hard to read text
before public class LockShackle2
It's an attribute
is there a command for code
nvm
`using UnityEngine;
[RequireComponent(typeof(Animator))] public class LockShackle2 : MonoBehaviour
{
private Animator anim;
private void Start()
{
anim = GetComponent<Animator>();
if (anim == null)
{
Debug.LogError("Animator component not found!");
}
}
private void Update()
{
if (anim == null) return;
if (Input.GetMouseButtonDown(0) && isMouseOverObject())
{
anim.SetBool("isPlaying", true);
}
else if (Input.GetMouseButtonUp(0) || !isMouseOverObject())
{
anim.SetBool("isPlaying", false);
}
}
private bool isMouseOverObject()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
return Physics.Raycast(ray, out RaycastHit hit) && hit.collider.gameObject == gameObject;
}
}`
this is what it looks like now @soft shard
i added it
it says the script class cannot be found when i try to attach it to my shackle
There is a !code command in this server (forgot about that lol), I think your using 1 backtick, youd want to use 3 for the correct formatting - you can also edit a previous message if you right-click it
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Also, do you have any compile errors in your console?
no
[RequireComponent(typeof(Animator))] public class LockShackle2 : MonoBehaviour
{
private Animator anim;
private void Start()
{
anim = GetComponent<Animator>();
if (anim == null)
{
Debug.LogError("Animator component not found!");
}
}
private void Update()
{
if (anim == null) return;
if (Input.GetMouseButtonDown(0) && isMouseOverObject())
{
anim.SetBool("isPlaying", true);
}
else if (Input.GetMouseButtonUp(0) || !isMouseOverObject())
{
anim.SetBool("isPlaying", false);
}
}
private bool isMouseOverObject()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
return Physics.Raycast(ray, out RaycastHit hit) && hit.collider.gameObject == gameObject;
}
}```
ah like that
look through it and tell me if anythings wrong with it
whats causing the class error
Is the script in Unity named the exact same as your class?
both are named Lock Shackle 2
and MonoBehaviour
Can you show the exact message that your getting when you attach your script?
"Can't add script component 'LockShackle2' because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match."
i decided to add the script to the original but
the animation just plays automatically
instead of waiting for my clicks
What do you mean by the "original"? And when you say "the script" are you referring to "LockShackle2" specifically? - that message suggests you have an error you may not be seeing in your console or IDE, or maybe you didnt save your script changes
LockShackle2 is a different version of an original LockShackle script
Well then if your first one works, why not move your code from the second one into your first one?
i did
it still dont work
ill send you the file and you can help fix it
If by "send the file" you mean posting the updated code here, sure go for it
i meant unity file
Maybe you can record a video instead, if you think the issue is beyond just looking at the script
fair
that didnt work
ill send you the animation and basic model
and you try to teach me how I was supposed to code it
there we go
@soft shard
Youd have to upload a mp4 for it to show up as a video on Discord, if you think all those files are needed for this issue, its better to record a video showing all your steps and setup, instead of sending files
the file was for unity
nvm it dont work
imma go to sleep
you wanna keep working on it tomorrow?
i can get on at like 4 pm
Well this is a public chat, so if you still cannot figure it out next time you work on it, you can always ask your question again, with as much info and relevant visuals, and im sure someone may be able to help if they can - its unlikely many will want to download a file to help though
Thats alright, no need to DM me for this, you can just ask your question here, and if someone can answer they might, doesnt have to be me
Using this code, whenever I pick up the item it's meant to show that you've picked it up in your hotbar, for some reason whenever I pick up the item it doesn't show the image. Could it be because I'm deleting the item before the sprite takes effect??
A tool for sharing your source code with the world!
eh... do you have a missing script on a gameobject by any chance?
scene or prefab one
Bump
I don't think so I'll take some photos of the inventory system.
It's annoying to go all the way up every time. If the message is buried, just repost it.
I've spent the last 5 hours trying to figure out whats wrong.
Where is it supposed to show the image? And what part of code is responsible for that?
The image is meant to be in the 3 boxes. & the code for actually showing it I believe is in ItemSlots I believe
Hey I have this LogStringtoConsole making a lot of garbage and cpus spike, but I can't really see where it's coming from... and what's weird is that i'm not outputting loads to console so I don't really get it.
Hey guys, im having some issues with a line renderer projection
private void LineRendererTrajectory(Vector3 startPosition, Vector3 direction, float totalDistance)
{
LR.positionCount = 2;
LR.SetPosition(0, startPosition);
Vector3 currentDirection = direction.normalized;
int obstacleLayer = LayerMask.GetMask("Obstacle");
Ray ray = new Ray(startPosition, currentDirection);
if (Physics.Raycast(ray, out RaycastHit hit, totalDistance, obstacleLayer))
{
float remainingDistance = totalDistance - Vector3.Distance(startPosition, hit.point);
LR.SetPosition(1, hit.point);
Vector3 reflectedDirection = Vector3.Reflect(currentDirection, hit.normal);
Vector3 finalPoint = hit.point + reflectedDirection * remainingDistance;
LR.positionCount = 3;
LR.SetPosition(2, finalPoint);
}
else
{
Vector3 endPos = startPosition + currentDirection * totalDistance;
LR.SetPosition(1, endPos);
}
}
This is my method here, the issue can be seen in the video
https://streamable.com/tswd71
When the second line reflects back into the original one and 10* within it, the lines shape is kind of weird, and im unable to find a solution on how to make it consistent
Aight thanks
Well I would look for a coroutine in your behaviour manager. You probably have logs turned off in the console
You should start with fixing your ui slots. According to the gizmos there's something really wrong with it.
ok I'm dumb I had collapsed on and didn't see one of them spamming, ta
Wait really?
Don't you see that the gizmos don't align with anything? And the fact that you get negative values for width and height should ring a bell too.
One top on working with ui: make sure that it works as expected by hand first before even touching code.
Ok, yeah this is my first time messing around with UI's I'll keep that into acount.
I'll change it up tomorrow & hopefully that's all thats wrong with it
Rather than code, it's an issue with the line renderer itself. I think there should be a relevant setting. The issue is that a line renderer is always have to create a quad, and if there's a weird angle close to 0 it would have to do the weird stretching to be valid. I think. Anyways, sharing the line renderer setting would help.
i desperately want someone to look at my project and tell me what im doing wrong, its UI something
I have a question, I am trying to figure out how I can basicly create 2 scriptableObjects then make one a parent or child of the other one, within code.
This is what I have so far:
DrawGrid newGrid = ScriptableObject.CreateInstance<DrawGrid>();
I am using this to create a scriptableObject
//parent the object somehow.
//save using the set path AssetDatabase.CreateAsset(newGrid, path);
AssetDatabase.SaveAssets();
I keep scratching my head on this, any help would be great!
ScriptableObjects don't have parent/child relationships
save the first one, then do AssetDatabase.AddObjectToAsset, is that what you mean?
Might be, I am trying for something like this
ah ya I think this will work thank you!
Hey, how would you go about making a 2D eye follow (UV Offset) work in 3d space?
Like if a character has eyes that are non circular (non-rotatable) and you need to UV offset, but have it follow the target?
Been having difficulty trying to figure out a setup.
Something about setting constraints and then normalizing the distance between the model's "eyeball position" and the look target. Having an anchor for each eye socket, as well as lookat (L/R)
Haven't found much info online since it seems like most folks use regular round eyes and rotation
wouldn't it basically just be offsetting the UV by the direction towards the target?
e.g.
Vector2 dirToTarget = targetPos - eyePos;```
hmm, i'll give that a shot and see if it works
Sounds like a trig problem
You need to pick a pivot point for the eye, which sits behind the 2D eye texture
If the eye mesh is spherical, then use the center of the sphere
otherwise, just pick a point that's...kind of where the center of a sphere would be?
You then need to know how much angular deflection (so, how much the angle changes) you get by moving from 0.5 to 0 or 1
hopefully this thing is radially symmetric, so that [1,0.5] and [0.5,1] have the same deflection
you do need to also know which direction the eyes turn in when you change U and V
that's a bit fiddly
Suppose you now know that:
- U deflects by 20 degrees on the +Y axis
- V deflects by 20 degrees on the +Z axis
Given a direction, you need to measure the signed angle between it and the eye's forward vector
You'd do so on both the +Y and +Z axes. If the +Y axis angle is -10 degrees, you'll set U to 0.25, since U covers the [-20...20] range
I'm not sure if a linear remap is the correct thing to do here
you might need to take the cosine of everything first
but that's just guessing
Of course, you'd do this after transforming from a world-space direction to a local-space direction for the eye
I would figure this out by using empty objects to mark the edges.
So you'd do a maximum positive U offset, put an object there, then repeat for the other three offsets
The annoying part here is mapping from a local-space direction to a UV offset
(it's almost the exact same problem that i was just describing in #archived-shaders !)
just phrased differently
moved to #💻┃code-beginner
Hello, silly question, but how do I check if a gameobject reference set in inspector is a reference to an existing object in the scene (or prefab instantiated) or a reference to a prefab in the Project Explorer?
Click once on it and see what gets highlighted
one cheeky way in code is if (myReference.GetInstanceID() > 0) // it's a prefab
errr - is that right? I'm workign off memory here
let me check that
but yeah do you want to know in code or just in the editor
Oh, in code, yeah
In code, yeah 😄
I find it odd that you would have a situation where your code needs to dynamically check that at runtime
I'm pretty sure assets are positive IDs, I feel like I've seen more negatives, I think you remembered correctly
what's the use case
Basically, there's one object that should be on scene for other scripts to grab at the start. If there's none, it will try to spawn one from scratch. Since this is for a tool, i'm allowing other users to set their own, and i want to support both assigning an already object in the scene as reference or a prefab and then spawning it
But im probably just gonna do it another way, wanted to do a quick fix, but better to have it well written
This tells you if the object was loaded from a file
which generally tells you that it's a prefab
Does Unity have a different definition of "loaded" when in context of SceneManager.sceneLoaded ?
I'm seeing in editor and on a built exe that finding an object that only exists in the scene that is supposed to have loaded fails.
The only way I can reliably find this object is if I depend on the AsyncOperation's .completed callback--but nothing in the docs indicates this.
Using 2022.3.38
hey, i have a problem and im not sure how to fix it
i have a hollow box that moves, and inside it i have a cube
now when the box stops moving, the cube moves (newtons 1st law) and it hits my box and makes it move extra. i do not want that
how can i do it
maybe the moving hollow box when it stops can be set to static/ kinematic until it needs to move again
ill try that, but from what im seeing, its being hit from the inside while its slowing down, before it reaches full stop
yeah that didnt work
i tried increasing the mass but that didnt seem to help
making it kinematic would make it not respond to forces, so it would work. though do you need this object to ever respond to forces?
if its kinematic lol
probably easier to fake forces on this kinematic if needed
on what way?
i see its kinematic and its still getting kicked around by the cube inside
is this 2d or 3d ?
2d
ah..kinematic in 2D works a bit different..

setting linear velocity
ahh
if you use addforce you don't get that behavior afaik
actually iirc it should still work, something is def not set correct on your end
wdym it should still work
You shouldn't be able to push a kinematic afaik
my unity is broken then lol
idk maybe show setup and some code
for me even at really high mass the dynamics don't do anything to kine
(this is disabled gravity for reds btw and using linearVelocity = vector2.down * speed in fixed update)
interesting
i just dont think this solution will fit well to the project, bc its basically a platformer
I guess?..you haven't given much info to begin with
I have a setup where the player can climb slopes, and the gameobject rotates in accordance to the angle of the slope. However, when met in a situation where the player is right on the intersection of 2 different angled slopes, it jitters and rotates quickly between the 2 angles.
I tend to just scan root gameobjects. Make sure you aren't accidentally catching a sceneloaded event for the scene prior to the one you are looking for and unsubscribing.
one option is to do multiple raycasts and use the average of the slopes you find
Debug.DrawRay(rb.position,3f*Vector2.up,Color.white);
RaycastHit2D hit = Physics2D.Raycast(checkPos, -transform.up, slopeCheckDistance, whatIsGround);
Debug.DrawRay(checkPos,-transform.up*slopeCheckDistance,Color.red);
if (hit)
{
slopeNormalPerp = Vector2.Perpendicular(hit.normal).normalized;
slopeDownAngle = Vector2.SignedAngle(hit.normal, Vector2.up);
transform.rotation=Quaternion.Euler(0,0,-slopeDownAngle);
isOnSlope=slopeDownAngle!=0;
Debug.DrawRay(hit.point, slopeNormalPerp, Color.blue);
Debug.DrawRay(hit.point, hit.normal, Color.green);
}```
Hi, I have a utils repo that's maintained separately from any projects.
It now requires 2 dlls, Microsoft.Win32.Registry and System.Drawing.Common.
What is the best way to go about including these to avoid possible conflicts?
Have them as listed dependencies in the readme, include them in the utils directory and warn users about it, or does unity just handle these conflicts fine on it's own?
Thanks in advance and please @ me.
Are you talking about a game or a plugin?
I wanted to code a sort of save state for certain objects in a scene and you could reload them to their initial state on start (transforms, script variables, child objects, components and their variables etc.). Pretty much it's for resetting a puzzle without the need to reset the whole scene. However now that I'm thinking about it, maybe just making a separate prefab of prefabs I can just load is better?
So I have a directory(also a repository) with a lot of utilities I use in almost all my games.
It's a collection of scripts, sprites etc.
I am asking whether the plugins directory(where the 2 dlls I listed are) should be located in NnUtils or just mentioned in the readme that it's needed in order to avoid conflicts with other assets that might include these dlls or maybe even the base project itself.
This might be helpful to you. I don't think there's a perfect solution (yet) and won't be until Unity is on CoreCLR
https://discussions.unity.com/t/multiple-dlls-with-same-name-from-packages/825324
hi! i'm having an issue passing a CSV-ish file through into unity. i'm splitting the string by its commas and putting them into an array via String[] charactersArray = String x.Split(',');
it's also getting the returns/line breaks/newlines as a part of the array, which i want to remove. so far, i've tried removing it via regex by trying to trim \r, as well as the standard trim function in String.
I recommend simply using an off the shelf CSV parser so you don't have to deal with this nitty gritty stuff.
i find it weird that i'm doing exactly what the carriage return is, but it never seems to get removed?
But if you want to remove whitespace this is a good answer: https://stackoverflow.com/a/6219488
do you have any recommendations? i'm trying to do it myself because i want to make a simple to use level creation tool for anyone that wants to mod my project
see here where the array is storing returns as a part of the character