#archived-code-advanced
1 messages · Page 26 of 1
oh I see
I need to make the jobprefabs but now it still gives me a null despite it being filled
I am still not getting where is null because I got the job prefabs
You haven't shown you've done anything. Show your resources folder, show your updated code and errors
Show what you've debugged to indicate what is null
The prefabs I added in for the jobs
NullReferenceException: Object reference not set to an instance of an object
InitBattleState.SpawnTestUnits () (at Assets/Scripts/Controller/Battle States/InitBattleState.cs:43)
InitBattleState+<Init>d__1.MoveNext () (at Assets/Scripts/Controller/Battle States/InitBattleState.cs:17)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <f1212ad1dec44ce7b7147976b91869c3>:0)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
InitBattleState:Enter() (at Assets/Scripts/Controller/Battle States/InitBattleState.cs:10)
StateMachine:Transition(State) (at Assets/Scripts/Common/StateMachine/StateMachine.cs:38)
StateMachine:set_CurrentState(State) (at Assets/Scripts/Common/StateMachine/StateMachine.cs:10)
StateMachine:ChangeState() (at Assets/Scripts/Common/StateMachine/StateMachine.cs:24)
BattleController:Start() (at Assets/Scripts/Controller/BattleController.cs:20)
The updated error
43 is accessing unit, presumably the hero prefab does not have a Unit component on it.
Okay now I am okay
Some debugging would have shown you that. Post in #💻┃code-beginner or #archived-code-general next time
alright
is there any way by code to know if we are running the device simulator ?
Hi, is there any free scripts by which we can triangulate a polygon collider points to generate a mesh
PolygonCollider2D can do this:
https://docs.unity3d.com/ScriptReference/Collider2D.CreateMesh.html
how come my UIToolkit ToolbarMenu does not display the text
I can see it holds the text in UI debugger, but it is not displayed
thanks
I found the issue. categorySelector.menu.MenuItems().Clear(); instead of categorySelector.Clear()
@hollow plinth Please read #📖┃code-of-conduct
Gonna try this again. Believe me, if I could stop trying to solve this problem I would, but my company needs me to be able to use Unity.
Is there ANY WAY AT ALL to determine why 'reload script assemblies' sometimes never completes? Like a log of what it is doing, or a memory profiler for that process, or anything? I'm begging here on my hands and knees.
I'll literally pay you money
how do u find the child of an object
foreach (Transform child in transform)
ok thank u
how do i get the script of a child
sorry
Thank you, no that was exactly what I needed, just some clarification if that was actually happening.
and thank you too @brisk pasture
I like Praetor. He doesn’t answer the question, he gives you just enough to start your Google search, which often leads to you learning more than you would if you were just given the answer.
And he does it without sounding like an elitist prick. Looking at you, StackOverflow.
Reminds me a lot of Eric5h5 from the forums.
its how the majority of this should Go
#💻┃code-beginner could not help. maybe you guys can?
public class Spawner : MonoBehaviour
{
// i got a round building and want to search the next free spawnpoint for a unit with this Physics.CheckSphere script.
public LayerMask mask; // The Mask where CheckSphere is searching in
public Vector3 spawnCheckerResetPosition; // Reset Vector3 for the "Searcher"
public Vector3 freeSpawnPoint; // Vector3 of the first free spot found
public GameObject unitPrefab; // GameObject i want to Spawn
public bool foundSpawnPoint;
private void Start()
{
//InvokeRepeating("Spawn", 2.0f, 1f); // not using this right now
spawnCheckerResetPosition = new Vector3(transform.parent.position.x + 0.5f, transform.parent.position.y, transform.parent.position.z); // set position of the reset point
}
void Update()
{
CheckSpawn();
if (foundSpawnPoint)
{
Spawn();
}
}
void CheckSpawn()
{
if (!Physics.CheckSphere(transform.position, 0.5f, mask))
{
transform.RotateAround(transform.parent.position, new Vector3(0, 1, 0), 360 * Time.deltaTime * 5); //this is the Searcher
transform.Translate(-0.01f * Time.deltaTime * 20, 0, 0);
}
if (Physics.CheckSphere(transform.position, 0.5f, mask))
{
freeSpawnPoint = transform.position;
foundSpawnPoint = true;
transform.position = spawnCheckerResetPosition;
}
}
void Spawn()
{
Instantiate(unitPrefab, freeSpawnPoint, Quaternion.identity);
foundSpawnPoint = false;
}
}```
is there a runtime equivalent of the editor action when you set the inspector to Debug and you replace a script by clicking the script reference in a component?
I don't think so.. I guess it's equivalent to "serialized current component -> remove current component -> add new component -> deserialize to new component"
^ And unfortunately Unity doesn't let us use their serializer in binary form so you're stuck with serializing to/from JSON
i ended up copying then destroying...
Is there some other method I should be calling here to resize a UI element at runtime?
oldRect.rect.Set(oldRect.position.x, oldRect.position.y, oldRect.sizeDelta.x, Mathf.Lerp(oldRect.sizeDelta.y, 100, 0.1f));
You are calling method to return value of a property… never use Rect.Set method
Set sizeDelta to resize it.
you should be using DOTween to animate the size of UGUI elements (recttransforms)
try to write this as a coroutine
in my experience, that error occurs in very complex projects with a lot of asset store assets. those things tend to depend a lot on editor lifecycle stuff that is pretty toxic
you can run the profiler and enable it in edit mode, then hit play and see what happens
in my experience that error occurs in
Can I get the external editor preference somehow
I want to use a known working editor to edit a file that is outside of the project tree
Is there any good way to check if matrices are nearly equal for unit tests? Assert.AreEqual returns false as there seem to be some rounding issues beyond the displayed digits but there is no specific overload that takes matrices and a delta.
no, author your own check. iterate through each element.
Yeah thats what I did. I hoped there was a cleaner solution
What do you guys use for websocket client, ClientWebSocket or something else?
probably a better question for #↕️┃editor-extensions
I have a subclass of ScriptableObject, say "MyScriptableObject", that has a single static variable called "instance" representing a singleton for the class.
In the Awake() method (called when the ScriptableObject is created via the Editor menu item), I do the following:
instance = this;
I set a breakpoint and confirm Awake() is being called and that "instance" is set.
However, when I run my app and access MyScriptableObject.instance, the value is null, as though it's never been set.
Any ideas?
I have a subclass of ScriptableObject, say "MyScriptableObject",
uh oh.
we got one
i have used websocketsharp for as long as i still used websockets
Thanks, how does it compare to ClientWebSocket?
i've never used it, and i have no reason to believe it is implemented fully in unity
Interesting, I'd prefer built in over a third party dependency tbh, I guess I'll have to investigate.
SO's Awake will not be called until you actually load it. You should not use singleton and mutable SO but seems like you are using both 🤔
Hey everyone! My code works perfectly fine when i have it in debug mode but the moment i let it run without stepping through it breaks
And the code is?
The code is supposed to get to the zones in the list and reveal them as soon as it lands on the zone and then it should be transitioning to the next one and do the same until there are no more zzones but currently its bugging out. Like it'll either reveal one and then stay there or it'll revel two and then go the the third one and stay there and not move
I've rebaked the nav mesh and everything
@jolly token ?
And which part are you stepping through in debug mode?
Can't tell what is 'zone' though, is it suppose to be some kind of game object on navmesh?
the Coruotine method is the part im stepping through @jolly token
And yes that is correct
The zones are gameobjects , and i have a ground with a navmesh on it and the thing is that is was working perfectly and then i made my field bigger and then rebaked the mesh and this is when the problem started happening
Okay, so that means WaitUntil condition waits correctly when you are using debugger, but does not wait or wait forever when you are not using debugger?
Exactly!!
like i just ran it now, and it was working fine and revealed two zones and then when it got to the third one, it didnt reveal it and just stood there
Maybe make it into while loop (instead of WaitUntil) and log the navmesh agent values in the loop?
Path state and position, remainingDistance etc..
So you can see what is going on when not using debugger
Like it's decide when or when not to work
Yeah those kinda bugs usually have issue with timing
I just removed the agent.hasPath part of the WaitUntil and its working...
@jolly token
So i assumed it couldnt find a path
Hmm maybe it's 'arrived' and path is not valid anymore
When you're using debugger maybe deltaTime is different and the condition can be both true?
Yeah that's probably what it was
Anyway, i removed it and its been working as expected! Thanks @jolly token
Glad it works 🙂
Thank you for the response. My understanding based on docs (and catching it with a breakpoint) is that the ScriptableObject.Awake() is called when you create it in the Editor; not after the fact, when you run the app.
I'm not clear on what you mean by "you should not use a singleton and an SO"
what would be a good approach for combining root motion and in place animations ?
so far I tried using StateMachineBehavior that enable and disable applyRootMotion on the animator
it worked fine, until a case with character facing came up (some states need to rotate the game object over Y before playing the animation)
I can solve this by creating specialized StateMachineBehaviors for each state that needs something like that, but it feels like a wrong solution
I just started dealing with animations, so don't know the good practices
even the general StateMachineBehavior I mentioned also feels hacky, because I have to add it to every state
to give more details - I want basic locomotion to use in place animations
and things like skills and special locomotion (dash) to use root motion animations
What is a coroutine? Let me check google 😄
Hopefully this is the right place to ask this.
I'm trying to instantiate objects in an arc in front of a boss. I've tried using the Boss' transform.forward, but no matter where it's facing, the objects always spawn in the same pattern, facing forward on the world's Z axis.
Not sure if the parenting is weird, but I'm using the top most parent and I've made sure that whenever it's rotating, the Y axis on that transform is moving around
https://gdl.space/otipuhekuy.cs
I need to change the material alpha to not multiply between particles, what would I need to change in there? and yes I need to do it thru code
private static readonly int SrcBlend = Shader.PropertyToID("_SrcBlend");
private static readonly int DstBlend = Shader.PropertyToID("_DstBlend");
private static readonly int ZWrite = Shader.PropertyToID("_ZWrite");
public static void ToFadeMode(Material material)
{
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt(SrcBlend, (int) UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt(DstBlend, (int) UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt(ZWrite, 0);
material.DisableKeyword("_ALPHATEST_ON");
material.EnableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int) UnityEngine.Rendering.RenderQueue.Transparent;
}
Anyone know how to cap/or limit the growth of ContentSizeFitter?
As far as I know, you can use "Min Width/Height" in any LayoutGroup to set the minimum...
You then use ContentSizeFitter to let it grow based on the size of its content...
But then how do you cap it at a X amount?
is this the proper channel to ask for help?
Depends. Advanced code? Yes
only for advanced code problems
Otherwise #🔎┃find-a-channel has the channel list + descriptions
Not part of its design
cap what at X?
you can put it inside another object
what are you trying to content size fit?
it's kind of an oxymoron what you are trying to do
it sounds like you want to use a horizontal/vertical layout group instead
not really a coding question though
A chat bubble that starts off as small as the text inside, but grows its width as the text increases, up to a width cap,
then it expands vertically (down) indefinitely, or even this up to a cap, after which, the text turns to ellipse.
padding
having engineered something exactly like this, UGUI doesn't have a built in way to bubble up layout from a child to a parent, which is your actual problem
@limpid prairie
@limpid prairie welcome to try at https://d2v2m3z6005g8q.cloudfront.net/ and use the source
without the hierarhcy this is going to be hard to see
I just fixed it
I overrode some UI Layout code from unity
Thank for that resource tho! That looks like a fun game
I am trying to make movement for player based on my own simple state machine.
This player movement module supposedly works so that MovementAction-s listen to event OnActivation and OnDeactivation in State-s which can be activated and deactivated by the state machine with only one state being active at a time.
There may be such MovementAction-s as for example MoveAction and JumpAction which would be able to connect to such states as OnGroundState or InAirState. If JumpAction is connected to InAirState the action will work regardless because it doesn't care to which state it is connected.
My hierarchy for this code currently is MovementAction>StateMachine>States, so MovementAction and StateMachine provide some interfaces which are then implemented in StateMachine and States. I made the hierarchy this way because I thought the thing I needed was movement which is implemented in MovementAction so everything else must be details of implementation of MovementAction.
But now I have a feeling that I should place StateMachine on the top because there has to be a moment in time when I will activate the entire movement module and there has to be something exact activated by this action (regular word) such as an object implementing ILauncher which would be the StateMachine and in this sense the StateMachine is also controlling everything.
I am asking for clarification on what approach I should use and what's wrong and/or correct in my thoughts on this topic. From answer to this post I want to get precious experience which I would be able to use in other hierarchies.
Thank you.
okay great. my memory is doing this richly is hard. i also did recycling scrolling
anyone know how to access the lens flare component via script? seems to only work for built in render pipeline Lens Flare and not SRP
Has anyone experienced this huge lag when you click the middle button of the mouse in scene view?
This might only occur after you have worked a while ago.
Here's the deep profile stack trace I managed to obtain.
thanks, didn't see that
Unity's built in GetComponent API fails to account for generic covariants
It's a niche use case, but I just stumbled upon this bug and had to write a custom GetComponent function that accounts for it
I'll file this as a bug
can you give an example just curious cause i use this too and haven't encountered any issues
yea sure
so basically, I have an IProvider<out T> interface
assume I use IProvider<IItem>
technically, you can cast this to IProvider<object>
I tried to use GetComponent<IProvider<object>>() to get a reference to my IProvider<IItem> implementing MonoBehaviour, but it returns null
I hope this illustrates the example well!
that doesn't look like a bug
well, it should return my IProvider<IItem> when I use GetComponent<IProvider<object>>()
but that causes other issues
which are
like if you actually had a type of IProvider<object>
and if you had many other types
how would it know which one to get you
you can use GetComponent<MonoBehaviour> and it just returns you the first monobehaviour, not really an argument imo
just the nature of OOP
for getting specific ones, you can use the GetComponent(Type) overload
huh wait you can add the same monob onto a object?
wdym
thought components were unique
yea?
what are you talkin gabout
all your custom components inherit from MonoBehaviour lol
Well yea, in the case of that its the generic argument of the function overload
na passing in monob
so if you had just
some abstract class
that inherited monob
could you do GetComponent<abstract>
yea ofc that works haha
and then get one of them back
dont tell me you didnt know
unity does the compare does it not?
I'm pretty sure the implementation is in C++, so I have no idea what it does
It most likely does not use C#, for example using Object is AbstractClass syntax
i don't think IProvider<object> and any IProvider<out T> is the same in this case anyway
with the comparison you are referring to
it's not exactly the same, no, but since GetComponent accounts for inheritance, it also should account for generic covariants.
It's only valid for <out T>.
right
Btw it’s allowed to add same component unless it has https://docs.unity3d.com/ScriptReference/DisallowMultipleComponent.html
Hmmm yeah they’re probably just comparing C# Type from C++ side, it should be considered bug hopefully they fix it.. 🫠
I'm guessing that too
I compiled a build twice on the same PC and diff'd the outputs and found that globalgamemanagers was the only binary file that was different. I'd like to see if someone here knows A: If it is expected behavior for 2 builds to output the same result, and B: Why they may differ (other than just saying it's compiler magic)
Diffing the globalgamemanager files between the two builds (in the latest test) produces just 1 line difference. I might just chock that up to a time stamp being different? Ah I see the buildGUID. I will test with the No GUID option and rediff
Also yeah the result should be deterministic if you turn on deterministic compilation build option (from player settings)
cathei can you answer my question which is approximately 60 messages behind? It's on topic of architecture decision
also cathei you often answer various questions and I wonder what qualifications you have? like middle, senior, or something?
I don't see the deterministic option in PlayerSettings using my build script, I'll check in the editor.
are you trying to make your own CI/CD pipeline?
i vaguely recall
Not at this time, this is for a minor CPU comparison for builds. Triple checking to make sure that the CPU's we build with will work with the CPU's we use on our boards
CPU's we build with will work with the CPU's we use on our boards
hmmmm...
Nvm, it was already enabled
you're building on Windows right?
and boards... do you mean, for like a computer in a car? or a certain money-related spinny appliance?
spinny appliance heh
lol
okay
i can imagine there are a lot of special requirements. are the spinnies running windows or linux?
or android
imo, the best thing to do is to not build il2cpp
Windows. It's mostly just to see if we can use AMD cpus to build with
Which I'm 99% sure we can
just a sanity check which has rabbit holed into diffing binary files
building il2cpp from the editor on windows always works. headless windows il2cpp does not always work. usually never on any other platform, for a clean pipeline
mono always builds correctly. i don't think the unity team tests building headlessly in il2cpp on anything but their idiosyncratic editor computers and their own cloud build servers
which have undocumented side effects
that occured on them a long time ago
for example they probably log into their windows build machines with RDP at least once, which causes all sorts of side effects
trust me
i run a unity ci/cd service
Yeah I understand it's hard to test for all those use cases
deterministic builds are really tricky. it seems like you ran into some of the basic issues. i only check certain files and folders
with mono builds, stuff like the player.exe can be kept, and is never replaced
Aha, I disabled the GUID and got identical build outputs!
This is using mono
great
headless
excellent
I feel like this requires an article to answer lol. For now I can say that it'd be best to try and see how it goes, and look into how other (open source) state machine / locomition implementations are. You could StateMachine and MovementAction both reference each other, that's fine too. Other people and I might be able to give better answer if you have some mini-example in code. We speaks in code 😄
you can also use game-ci's docker images for windows and mono. their il2cpp builds do not work - nobody's does. they think theirs do though
it's tricky
there is also some Brian McQuaid energy over there at game-ci
which may rub you the wrong way
How should I upload the code?
Nuvei sounds familiar
Also the point of the question is not to find out what is the best configuration for a state machine but to help me understand WHY an approach is better
Hmm I have been working for 10 yrs and had to do kinda everything including server, CI, optimization whatnot. Because team I've in was mostly small 😄
I think Gist is good so we can leave comments?
the best approach is to not author your own state machine framework
that said it sounds like this is for personal learning*
does 1 class for 60 lines sound like a framework to you?
It's like paste site, nothing hard. You can include multiple files in a post.
IMO it's easier to show/understand how it has "bad case" than how the approach is better than another.
Everything has trade off anyways, it's hard to say one is superior than another
so I upload all the code on the same page?
Yea if it's not too much files
what's the conditional compile keyword to detect if VisualScripting🤢 is installed?
Use version define on assembly definition?
how do you do that?I'm looking for something like #if UNITY_VISUALSCRIPTING
unity packages usually add themselves here, or used to
Uploaded base classes with 1 example each
Can you see it?
I can see, if you put the extension as .cs it will highlight
thanks!
should I reupload? or there is a way to change the extension?
Oh
I changed
Yeah that's good
Anyone know How I can take the "f" string format,
but modify this formatter such that, instead of:
Wednesday, November 9, 2022, 1:49:30 PM,
I get:
Nov 9, 1:49 PM ?
Hmm so this MovementAction resembles StateMachineBehaviour in Mecanim. Have you used them before?
Yeah I did but not in code so not sure what the Behaviour is
I think it would make sense to make an API like it
https://docs.unity3d.com/ScriptReference/StateMachineBehaviour.html
It's like MonoBehaviour, but you attach to State instead of GameObject.
I think you want reusable feature for multiple state, so that is pretty close
If you think of Mecanim, State is just an entity, does not have characteristic.
Then maybe you can think of making OnGroundState as OnGroundBehaviour and JumpAction as JumpBehaviour, and attach them into same state. It will make the layout plain, and you don't have to think too much of what should be MovementAction and what is State.
I think it isn't what I was asking about... I had 2 approaches in my mind:
- StateMachine should be atop the hierarchy because there has to be a point in a program which would launch everything else and StateMachine looks like a good candidate for it.
- MovementAction should be atop the hierarchy because it's my intention to move the character and everything else is just implementation detail.
And I was asking which is more correct should I say from the point of building an object oriented application with nice changeability?
there is documentation online for date format strings. however, due to limitations in unity, you should probably use a dedicated time library like NodaTime
So I'm saying your MovementAction is pretty similar to StateMachineBehaviour. It even has a [SharedBetweenAnimators] which make it independent from individual Animator = StateMachine.
That being said, I would say you can reuse MovementAction across multiple StateMachine if you need, but StateMachine should still be on top of hierarchy, in a context of a state machine.
Everything besides your last message so far looks like evaluation or understanding of my code and only the last one looks close to what I was asking about. Not trying to offend, it just looks this way to me so far, not sure if it's so tho
I dont want to hijack the discussion but I'm just curious if anyone is using com.ai.navigation (the navmeshcomponents thing) and could elucidate for me the intended method to execute NavMeshLinks manually as opposed to the old OffMeshLinks. I've already figured out how to get a reference to the NavMeshLink by casting the navMeshOwner on the agent to the right type, but I'm curious as to how I can leverage the NavMeshLink now being an area. Getting a reference to the component obviously just gives me the start and endpoint, not the path the agent is intending to take through the link's area. It's perfectly functional as is but I feel like I'm missing some of the new features by doing this. Are the intended traversal points contained within the calculated path? If so, isn't that odd since it's not necessarily obvious which points on the path are relevant to the link?
And before someone says - yes I've asked in the AI channel several times, it doesn't seem that anybody over there is using the new navigation package or knows how to use the new links.
(I am manually animating the movement between the links through code since I need the agents to do special stuff when they cross it such as walk to a door switch and play an animation to open the door prior to crossing the link)
i think you have to put the agent and the graphics on different game objects
since it sounds like your issue is related to rigging, and you are correctly using navmesh links
you can fork the source and make whatever changes you want too
Just let him cross naturally and then reconstitute the intended animation path based on what the agent did???? That sounds gory as fuck
I really hope there's a better way but yeah, I guess that could work. The agent and the graphics are already seperate in my system by the way
are you asking someone to read the package's source code to find "the path the agent is intending to take through the link's area"?
Noooo not at all
I'm wondering what the new equivalent of OffMeshLinkData is essentially
that soundsl ike it would be the solution youa re looking for though
like for the purposes of rigging this animation
Like with the old system there was a struct that contained all the traversal information for the agent. The start pos, end pos, link type and a reference to the offmeshlink concerned
I'm just trying to figure out if com.ai.navigation has a thing that's similar to this at all. It seems like a really basic requirement that would be relevant to anyone seriously using the new system, so I was wondering if anyone is using it since they probably would know
do you mean like this? https://github.com/needle-mirror/com.unity.ai.navigation/blob/5355cfb57e645b2eaf59fb90ce87d7220468f4bc/Runtime/NavMeshLink.cs#L142
I’m trying to give you example of how other state machine system solves similar problem, so you can improve your system. But I guess you prefer yes/no answer.
it sounds like you want the field NavMeshLinkInstance m_LinkInstance = new NavMeshLinkInstance();
you can create a subclass of NavMeshLink and create a property for it
I don't think that's it
NavMesh.AddLink just adds a link to the navmesh. So the information contained doesn't have anything to do with the path of the actor, I think
I haven't tested this yet since I just found out about it but I'm guessing that the start and endpoints here just match the start and endpoints that are set in the link component
I'm talking about the specific start and endpoints on the area defined by the link which the agent is intending to take
how would you achieve this in "the old code"
The old code it was a line, so it didn't matter. But it was contained in the OffMeshLinkData, a struct which was generated when an agent would take an offmeshlink
But yeah the offmeshlink just has a start and endpoint
NavMeshLinks on the other hand are now areas
I've already designed the game to use simple start and endpoints for the locations where agents leave the navmesh so it isn't really the end of the world but I feel like there's probably someone out there that's using this package that has an answer to this question
okay well then make the width of the thing the width of your agent
and it will prob cross in the midpoint of the two edges
you're confident it's an area right?
Well currently my states have function bool IsSuitedToBeApplied() which checks the state's condition for not forcefully entering it. For OnGroundState it would be if the player is grounded. Then when someone says to state machine I don't care what state you will be in after but not the current one - SetState(null) state machine will check the spare states' conditions and choose the first suited to be applied now as the new active one
i mean i know it looks that way in the editor
you're confident it doesn't always cross through the "middle"?
I don't think it would easily work with what you are suggesting, would it?
I'm not confident at all, I am just seeing that it is an area and assuming that that's relevant somehow
:S
To clarify, with offmeshlinks:
- Wait for agent.isOnOffMeshLink to be true
- Read agent.currentOffMeshLinkData, which contains the start and endpoints for the crossing and a reference to the link
With navmeshlinks:
- Wait for agent.isOnOffMeshLink to be true
- Check that navMeshAgent.currentOffMeshLinkData.offMeshLink == null, which means it's a navmeshlink ಠ_ಠ
- Cast navMeshAgent.navMeshOwner to UnityEngine.AI.NavMeshLink, which gives you the navmeshlink it's crossing
- Now we only have access to the start and end points of the link, so it just crosses the middle of the link, not making use of the new feature where links are areas instead of lines
Jank.exe but it works, I just feel like I'm actually not doing it the right way because now my agents just still can only cross in the middle of the area
Maybe the area thing is just not implemented or some shit. It is under construction, I guess
Hmmm IsSuitedToBeApplied() or SetState(anything but current one) is not really common in state machine. State machine is essentially a definition of states and transition between them. So it usually would check for transitions that goes out from current state (not from/to any states)
I'm not judging, btw. I'm saying it's not common approach, and there is usually a reason when something is not commonly used than the other. In this case the reason would be 'it's hard to control where the transition comes and goes'.
i think they always only crossed in the middle
it's not really an area now
the package is a wrapper around the familiar navmesh you've been using
the visualization in the link (width) is meant to show you the size of the agent that can pass
@tough knoll does that make sense?
you can prob get agent.currentOffMeshLinkData again if you want
Oh
Well in that case my current method works fine then yeah
That's kinda odd
Is this package a thing nobody uses or something? I understand the new features aren't incredibly useful but it's nice to be able to have individual navmeshes linked to the transforms of objects
also this kinda doesnt explain why area can be scaled on both axes, if it's only used to measure the width of the agent
it is a lightweight wrapper around NavMesh based on the "NavMesh Components Workflow" project
I'm creating a 3D bullet hell game.
When creating my weapon pool, would it be beneficial to create a dictionary containing a list of each different projectile type, or is it more practical to just use one list and assign the data to the projectile as I need it?
And when using 3D models, is it appropriate to change them on demand, or should that just be reused?
I think the reason would be extendability. So that I do not need to list all the possible states when I just want to quit current one
By the way I think I've come up with a solution
It's as for SetState(anything but current one)
Hello.
??? Are you literally asking how to bypass security process of app store?
its out of curiosity. he has not spoken how he will manage to bypass on purpose
I could not make him tell. But I wonder now.
Nice, what would be your solution? 😄
I'm pretty sure it's against to #📖┃code-of-conduct to discuss about illegal actions like this or decompiling.
hmm. I did not know that. let me check
Share or discuss any form of pirated or illegal content. found it
I love my account
My solution would be that my initial intention isn't to make MovementAction but to make player move. That can be achieved with all kinds of approaches like a state machine or a single class controlling all the player's movements. So I just will make an interface similar to IController with Enable and Disable methods. The interface will be implemented by state machine. The only question I have not thought about yet is how will be changing the states accessed by the movement actions
@jolly token I saw you typing something but then you stopped, perhaps you do not like my idea?
I dont know if this an advanced question but does anyone know a way to connect a bluetooth device to unity and read data off it?
maybe use a bridge like use a software to write it data to file then throw it in unity to read it?
Hi, I updated Ubuntu and it seems .Net stopped working on my machine. I get this error now: "The .NET Core SDK cannot be located: A valid dotnet installation could not be found. .NET Core debugging will not be enabled. Make sure the .NET Core SDK is installed and is on the path."
I installed full mono as requested, but still doesn't work
actually Unity works. Is VS Code that doesn't work
Install .net core sdk?
but the message says it requires full mono installation
maybe I need to specify the path? I have no idea where it is
trying to install .net core
Did you ever work out why this package was missing its meta files?
nope, figured out unity simply didn't want me to shove fsr in there. told myself i was gonna update to a new version of unity with actual fsr support but haven't even done that yet
in the end this worked for me https://stackoverflow.com/questions/73753672/a-fatal-error-occurred-the-folder-usr-share-dotnet-host-fxr-does-not-exist
This is doing my head in, im sure its a variance problem - but its too late (or im too stupid) to figure it out
Anyone able to give me some pointers?
Does AddTask need to be generic?
Yeah that looks good
That's what I thought, but it refuses to let BuildTask be cast to IGameTask<IPayload>
If I do this, I get an "Invalid Cast" exception
I got no clue on this one, sorry.
All good 🙂
Can you do as IGameTask<IPayload>?
Yeah, but it will always return null. I sort of understand why, I am trying to use contravariance and covariance at the same time almost - which would allow for crazy things.
at this point I'm moving forward with a completely gross fix til I rethink this all haha
Not that, I just not sure what to add while not knowing full picture of what you’re trying. Abstracting state machine to IController implies that you want other movement mecanism that implement it to work as well, which was not in our previous conversation so far
👀
No I do not want another IController it's just that after reading Agile Software Development (only to the part with SOLID and a bit after) I think that you can create nice object oriented hierarcheis based on what is your intention. I mean, I am trying to stick to Dependency Inversion Principle (as it looks agile to me) and by placing exactly what you want at the top of your hierarchy you can similarly do the same for the rest of your program and get it done in agile fashion. Tho it is only my humble opinion and I would like you to correct it and give any insights on this topic if possible.
This my understanding is the reason why I was asking all this "what should be at the top, movement action or state machine"
Hmm okay it gives more context. I'd have to say that you don't need more abstraction than you actually need. If you think your StateMachine will be only implementation of IController, then it's basically same thing but with additional abstraction layer. This might end up over-engineering. I'd see it practically easier to maintain if your other classes knows your state machine as state machine (maybe IStateMachine) not IController. Though I understand that you prefer using interface than actual implementation and finding an architecturally better solution.
Covariance and contravariance does not work with value types 😄
It will work when you change BuildTaskPayload to class,
But again in is contravariance, that will allow assigning IGameTask<IPayload> to IGameTask<BuildTaskPayload>, not the other way like you want.
this looks okay, but what is your objective? @mystic flume
hmm based on what i am reading you should not have use generic templated interfaces
you can use IGameTask but not IGameTask<T>
however you probably should have AbstractGameTask
who calls UpdateTask?
that method is the problem
Thanks for the reply! Turns out we were getting the same error due to an entirely different new unity bug.
hello guys, i have a prefab thats being instantiated and i would like somehow to retrieve the original prefab form the instantiated one in order to change the original values
how could i do this?
saving the original prefab path in a gameobject component of it ?
or can i somehow keep a reference to the original prefab in the instantiation?
newobj = Instantiate(prefab);
newobj.GetComponent<YourScript>().someField = prefab;
im trying to do it in edit mode
but what i want to achieve with this is to be able to retrieve the original one to modify it
with the prefabUtility
is there a way to get Animator's current frame root motion ?
I want to apply root motion position, but override the rotation, and it looks like Animator will discard any transform mutations that happened during a frame if ApplyBuiltinRootMotion was called
this doesnt give me the original prefab
i guess i need the path theres no other way
What does it give you then?
Prefabs are instances
no but i need, in editor, while in playing mode...
modify the prefab in the project folder
see
willyV4 has this
and i want to save values in those collections, but not in the instance
but in the original prefab
using
PrefabUtility
well prefabUtility is the only way i know of editing a prefab by code
If you have a reference to the prefab then it is the prefab in the project folder, it just doesn't save the changes to it normally. But this is more of a #↕️┃editor-extensions question.
so while playing editor i would mess with the values in the collections
yeah thats why i need to use PrefabUtility.
oki thanks
were can I seek help about memory profiling? I think I gor a memory leek so I took 2 spnap shots, but from what I see the diference in both are related to editor stuff?
can some one help me out
I dont have much "new" menmory alocated from the snap shot b
I dont know why the game is allocating so much managed heap and to the virutal machine (mono)
profile the player
humm ok thanks
btw do I need to use the memory profiling for that as well or just the normal profiler?
wait sorry, btw what do you mean by the "player" the character player or the unity game player?
this is a comparison with a game build
How do I get the text of an inputfield, through script? When I try to set the text of the inputfield (through script) it doesnt work, and stays empty.
yourTextField.text = ""
I'm building a bullet hell game, and I need tracking missiles. Since this game is run over a network, it was recommended to me that I use a particle system for projectiles, since the state is easier to sync.
I was wondering if a particle system is capable of doing tracking?
No but you can write a script to move the particle
you were already answered
Is there an event method for scriptable objects that is called during the life cycle as soon they've been created and added to the asset database?
The best I could get is an OnValidate, but technically the object hasn't actually been added to the asset database.
And as usual Unity's documentation on SO lifecycles is basically non-existent.
unity game player. so as you can see the editor uses a lot of resources.
Awake
But yeah so lifecycle methods are poorly defined and poorly documented
Awake doesn't seem to get called in Editor?
Unless it is being called, and I'm just expiriencing that bug where Unity just randomly stops calling editor events until you reboot it
It does, when you create the SO, AFAIK
I thought so first, but docs say:
This function is called when the ScriptableObject script is started.
Awake is called as the ScriptableObject script starts. This happens as the game is launched and is similar to MonoBehavior.Awake.
It says that but it's also not true AFAIK in the editor
It may be true in a build
but it may also not happen until the SO is loaded into memory somehow
I did some testing with that a while back and i'm fairly sure that it does get called when you initially create the instance in the editor, but then never again except in build
Yeah that's what my impression is too^
Alright. I just think that script is started leaves a lot of room for ambiguity 😅
This might work, thanks!
Unity debugger is saying I am not having UXMLFactory implementation
ofc I tried to generalise it in a base class which all panels in my game (menu, settings, game, shop) inherit from
but no, it is not working
here you go
I am doing it wrong isnt it? 🤔
Hello, wondering if someone could help me. How do I set the start and duration of a playableasset after it has already been created?
Does anyone know if it possible to set a setter for attributes? I am making a multiplayer tool and I have an attribute called syncvar. Variables with this attribute automatically get synced through the network. I want variables with this attribute only to be set by the server (there is a static bool which can be used to check if you are the server) or a client if it receives the data from the server. Otherwise I want to return an error if you want to set the variable. Is this possible, or should I just make it clear in the documentation of the tool that clients shouldnt set this variable
A typical netcode framework does exactly that. The logic for it needs to be implemented in the attribute itself and it’s underlying datastructure
yup i know, i just don't know where i can do that. I'm pretty new to working with custom attributes and reflection
from what I know I can't really put logic in attributes itself and need to use reflection for that
You don’t need reflection or custom attributes for that
An attribute is just another class
I am making the multiplayer tool, not using a tool
so i need to add this logic myself
In unity you can use the TypeCache to get to your attributes https://docs.unity3d.com/ScriptReference/TypeCache.html
Maybe explain what a multiplayer tool is
Well it's just the general mutliplayer logic what I'm writing. Sending data between server and clients. I have all the logic working, also for the syncvars. If you change the var on the server it gets synced for all clients. I just need to add some kind of logic that all variables with this attribute have a setter which checks if you are a server or are setting it through a function called when the data is sent from the server.
some popular frameworks (eg mirror) do it with a source generator or injecting IL (weaving). Easiest if you don’t want to use source generators is to make sync-vars a generic class which implements the required checks in its api
Netcode without some black magic done by source generators typically has a very verbose API and requires lots of boilerplate code
Source generators aren't really supported well in Unity iirc
You can do IL editing though
entities makes heavy use of them, but yes, cecil is more widespread still
Good morning, I am working with some custom build scripts and I was wondering if someone knew the BuildOptions value that corresponds with "Wait For Managed Debugger" in the Build Settings window. I am currently using BuildOptions.Developement and BuildOptions.AllowDebugging for the related options.
Can I change my Api Combatibility Level to .Net 4.7?
As in .net source generators? Recently I read that someone tried it out and couldnt get it to work properly 🤔
Or rather, code generation?
i haven't tried it myself, nomnom has afaik, docs are here https://docs.unity3d.com/Manual/roslyn-analyzers.html and i suppose there are some quirks
Source generators
You can use source generators as an additional step in your script compilation process. You can use source generators to add new code while you compile your existing code. Like analyzers, you can use existing source generators or create your own.
If anyone comes across this, it is BuildOptions.WaitForPlayerConnection
why? the .net framework option is saying, "an incomplete version of .net framework"
I have some custom build script and I use the following build option
bpo.options = BuildOptions.AutoRunPlayer | BuildOptions.AllowDebugging |...
Could someone explain why / how variables outside of a lambda expression remain in scope?
for (int i = 0; i < _inputNumberEventTriggers.Count; i++)
{
EventTrigger eventTriggerComponent = _inputNumberEventTriggers[i];
_mouseDownActions.Add(new UnityAction<BaseEventData>((BaseEventData) =>
{
GameObject elementGameObject = eventTriggerComponent.gameObject;
int number = i;
_isDragging = true;
Debug.Log($"Drag Index: {number}");
}));
_mouseReleaseActions.Add(new UnityAction<BaseEventData>((BaseEventData) =>
{
GameObject elementGameObject = eventTriggerComponent.gameObject;
int number = i;
_isDragging = false;
Debug.Log($"Drag Index: {number}");
}));
eventTriggerComponent.triggers[0].callback.AddListener(_mouseDownActions[i]);
eventTriggerComponent.triggers[1].callback.AddListener(_mouseReleaseActions[i]);
}
In this code I have a list of number buttons that I am adding drag listerns too, however once I play this in the game the debugs all come out with the number 9. Which would make sense if number was being set to i, but at this point i shouldn't exist.
I wrote the code again like this:
for (int i = 0; i < _inputNumberEventTriggers.Count; i++)
{
EventTrigger eventTriggerComponent = _inputNumberEventTriggers[i];
GameObject elementGameObject = eventTriggerComponent.gameObject;
int number = i;
_mouseDownActions.Add(new UnityAction<BaseEventData>((BaseEventData) =>
{
_isDragging = true;
Debug.Log($"Drag Index: {number}");
}));
_mouseReleaseActions.Add(new UnityAction<BaseEventData>((BaseEventData) =>
{
_isDragging = false;
Debug.Log($"Drag Index: {number}");
}));
eventTriggerComponent.triggers[0].callback.AddListener(_mouseDownActions[i]);
eventTriggerComponent.triggers[1].callback.AddListener(_mouseReleaseActions[i]);
}
Which does work, but the like with my previous statement with i, how does the variable number still exist? Are they only kept in memory because of the lambdas?
Sorry its a bit of a strange question, but its a concept I'd like to try to get my head around.
I cannot say I 100% know how it works under the hood. Basically the lambdas can either capture references to variables that are outside (your case 1) or they can create their own local values (case 2). Both are super useful.
you are a #archived-code-advanced developer using #💻┃code-beginner tools
anyway, int number = i was correctly moved. all the lambdas capture a reference to int i in the first example, which isn't redeclared in every loop, it is declared once, that is why this is confusing
there is only 1 int i. the code really looks like this:
{
int i = 0;
loop:
{
if (i < _inputNumberEventTriggers.Count) {
EventTrigger eventTriggerComponent = _inputNumberEventTriggers[i]; ...
...
eventTriggerComponent.triggers[1].callback.AddListener(_mouseReleaseActions[i]);
i++;
goto loop;
}
}
}
does that make sense?
so now it's unambiguous how it interacts with the lambda
that lambda rule becomes less nonsensical
it's confusing because of the way the iterator is declared, not because of lambda rules
🌈 don't use scriptable objects the way you are using them🌈
Why are lamda's considered beginner tools?
I do understand why I is the value it is when used within the functions, my confusion mainly comes from what values remain in memory. I was under the impression that objects or base types that exit a scope get dropped in memory / opened for garbage collection. Its something I never much paid mind too until now but the questions was mainly about how the language knows to keep these variables in memory rather then getting rid of them. And what other values will this have issues with.
i'm kidding - i meant the .AddListener
you have to use UniRx to do what you are doing
in the body
the meaty, meaningful part of your code
re: the GC scope
one perspective is referencing a variable in the lambda function ticks up its reference count
so even though it exits the scope of the for loop, it ticks down its references from (_inputNumberEventTriggers.Count + 1) to (_inputNumberEventTriggers.Count)
so it isn't going to be garbage collected
until the objects with the event listener fields are no longer referenced
because then, transitively, the lambda will not be referenced anywhere else
C# does not use automatic reference counting, but it's a way to see how something does or does not become eligible for garbage collection
yeah in C++, which i came to after c#, i can see how you have to be acutely aware of
is this thing ticking up a reference or ticking down, and who owns what
naturally, in c#, it's all shared pointers
Yeah, I have had a play with C++ in the past with shared and weak pointers, but didnt think much of that was carried over for C++ (in terms of developer usage)
to be more precise, it is an intrusive_ptr from Boost, and the destructor schedules destruction to happen later instead of immediately*
Out of interest then on a separate note, what would you suggest as the replacement for the .AddListner? I figure I might as well start looking into the better ways of doing this if there is one. (What I'm using it for is with the EventTrigger component for PointerDown and PointerUp events)
Gotcha
can you tell me what the UI is doing?
is it a list of things to select from?
like a list of buttons you want to add a handler to?
it's going to absolutely blow your mind how easy this is to do in unirx
Its a list of numbers at the bottom for the screen, the idea is to click and drag them too a target.
Its not very exciting, just part of a clincial test thing
using UniRx;
...
class ButtonListController : UIBehaviour {
void Start() {
var buttons = GetComponentsInChildren<Button>();
buttons
// now we have [button1, button2, button3]
// get the click streams from each button
// UniRx authored this helper, which is an extension method for UIBehaviour
.Select(button => button.OnPointerClickAsObservable()
// emits a tuple that includes the "number" we've associated with the button
// meant to illustrate how you can augment PointerEventData with extra stuff
.Select(pointerEventData => (pointerEventData, number: button.GetComponent<AssignedNumber>().number))
// now we have [[(button1click1, number1), (button1click2, number1)], [(button2click1, number2), (button2click2, number2)], ...]
// we want to flatten this into just an array of clicks, in the order of whichever is emitted ASAP
// [(button1click1, number1), (button2click1, number2), (button1click2, number1), (button2click2, number2)]
// so we'll merge all the click streams together
.Merge()
.Subscribe(tuple => {
var (pointerEventData, number) = tuple;
Debug.Log($"I clicked on number {number}");
})
// when ButtonListController is destroyed, clean up the handlers
.AddTo(this);
}
}
@abstract hill so that's it
it has OnBeginDragAsObservable and OnEndDragAsObservable
does that make sense @abstract hill
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public class RESTimageLoader : MonoBehaviour
{
public string filePath;
public SpriteRenderer Background;
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
var image = StartCoroutine(LoadTextureFromCache(filePath));
//Background.sprite = image;
}
}
IEnumerator LoadTextureFromCache(string filePath)
{
var www = UnityWebRequestTexture.GetTexture("file://" + filePath);
yield return www.SendWebRequest();
var texture = DownloadHandlerTexture.GetContent(www);
}
}
how would i set the sprite to the image retreived?
Thank you @undone coral, I'm a bit unsure on this right now so will need to re-read this in a bit. (Something has come up so I need to head off), I am defiantly interested in learning more though! Thank you, Ill have a look into UniRx properly too!
Thank you ^-^
Hey, can someone tell me if the way of writing these lines is correct or not? I'm not seeing any value changes, but it worked with simple numbers like 1 or 2 before. First time trying to get things like Mathf to work. I'm not seeing errors, but since I started using these equations it doesnt work anymore
movementFactor_value2 = 1 / 4007500 * Mathf.Cos(1 * (float)_mapRenderer.Center.LongitudeInDegrees) / 360;```
What I'm trying to write for value1 is 1 / 11132 * 2^20-ZoomLevel and for value 2 1 / 4007500 * Cos(1*Longitude) / 360
The first issue I can see is that you dividing integers, not floats. So you may just end up with the fractional part being lost.
1 / 11132 will equal something like 8.9 * 10^-5, as such when this is the cast back as an int this will equal 0
So your then are doing 0 * Mathf.Pow(2, 20...)
The Mathf.Pos code should work fine, you just need to make sure your working with floats
Simular problem with the second line of code,
MovementFactor_value2 will equal 0, since (1 / 4007500 == 0 due to them both being ints), then (0 * Cos(anything) == 0), and then 0 / 360 will equal 0
movementFactor_value1 = 1f / 11132f * Mathf.Pow(2f, (20f - _mapRenderer.ZoomLevel));
movementFactor_value2 = 1f / 4007500f * Mathf.Cos(1f * (float)_mapRenderer.Center.LongitudeInDegrees) / 360f;
Having f after the value should solve it
So I just convert all of them to floats?
Yeah, that should solve it, just putting f after the numbers will keep them as floats, which will then keep the values of the equations also as floats
Elsewise an equation between two ints will just convert it to another int
So you end up with loosing all your decimal values
Hmm, maybe it's not the equation being wrong at the moment but something instead. It's still not working after I converted them to floats.
But it's good to know, I definitely needed the decimal values
Thanks
The wrapping of an inputfield doesnt work, it just keeps going on the same line
Heyo! New here with a question: how do I get the screen position of a UI element? I'm trying to tween a RectTransform to position a child TMP_InputField directly above the virtual keyboard, but the code only works if the input field is a direct child of the parent object with the script that does the tweening. I want it to work with heirarchies of arbitrary depth so I can do more fancy UI stuff. anchoredPosition only returns the position relative to it's parent. I want to get the UI elements position relative to the root and I can't find a good way to do that.
I'm "tweening" a sprite from a spot in my 2d world to a specific point in my overlay/HUD. When needed, I create an Image on my UI canvas and tween it...
This is not 2D worldspace -> UI space. This is all UI space.
RectTransform still has position property.
It'd be world space position of your transform's pivot.
World space in UI?
does unity directx12 support multi-gpu? will it send graphics commands from different cameras to different queues?
does its directx11 SLI implementation... work?
Just world space, you can convert it to screen space if needed
Holy crow... so apparently the two scenes I was testing my code against used different canvas settings. One for Screen Space Camera and one for ScreenSpace overlay.
HOT DOG IT WORKS!
Has anyone figured out how to get FindWaterSurfaceHeight() with the new water system? I have been trying to figure it out all day I already have a buoyancy script I just need to find the Water Surface height a certain point
Hey, I've got this code ```public void CenteringButton()
{
if (_Centeringstatus == false)
{
_Centeringstatus = true;
_Centering_Shadow.effectColor = new Color(0f, 0.7f, 0.7f, 1f);
}
else
{
_Centeringstatus = false;
_Centering_Shadow.effectColor = new Color(0f, 0f, 0f, 1f);
}
}``` linked to a button in my UI.
The _Centeringstatus here is supposed to be false/true, and if it's true, it would let the timer do this LocationRefresh() here https://gdl.space/ebijijanex.cpp (code in link to shorten it)
It doesn't give me any errors, seems to work on my Android phone, but not on the AR glasses I'm programming for, which are Android 10. At the beginning of this script I'm requesting GPS data fetching permissions ```public void Start()
{
Panel();
EventSystem.current.SetSelectedGameObject(firstSelected);
if (!Permission.HasUserAuthorizedPermission(Permission.FineLocation))
{
Permission.RequestUserPermission(Permission.FineLocation);
Permission.RequestUserPermission(Permission.CoarseLocation);
}
}``` here.
This fetching, the timer, etc. worked when I didn't have it linked to the button but kept the timer going and going immediately beginning from the start of the app. But now that I'm trying to link it to the button it suddenly doesn't work anymore, so I think there might be a mistake in the way I used the _Centeringstatus bool here. Can anyone give me insight on what the exact issue is?
I have two objects, A and B. When A moves up and to the left relative to its forward direction I need object B to move up and left relative to its forward direction. This needs to work no matter what angle A or B are at.
My problem is no matter what I try it seems like it will move in the blue direction.
doesn't sound like an advanced issue. for help with code issues, it's also helpful to actually provide the relevant code. but anyway, to move something in the direction of it's forward axis you just move it by transform.forward * desiredDistance
I don't want it to just move forward, I want it to move to the left as well as forward. And I need the distance to be equal to how much A moved.
and again, that's not an advanced issue. and you still need to show code. also here's another hint: transform.TransformDirection exists
Or right and forward, or left and backwards, or up and left.
TransformDirection is local space, not relative to rotation.
you didn't bother reading what it does, did you?
I not only read it, I tried it.
this is a code channel mate. and you also just said you tried transform.TransformDirection. how did you do that without using code?
It's useless code because it's not even close to the solution.
I can post 10 different things I tried that did nothing but that doesn't really help anyone.
target.position = positionOffset;
target.position = target.TransformPoint(curPos - startPos);
target.rotation = rotationOffset * Quaternion.Inverse(startRot);
targetChild.rotation = target.rotation;
targetChild.localRotation = curRot;
target.rotation = targetChild.rotation;```
That's something I tried that didn't work.
It doesn't seem advanced until you actually try it. I thought it would be as simple as transformdirection too, but if there's no parent world and local are the same, it does not take facing direction into account.
literally all you need to do is get the distance and direction of movement from object A, use transform.TransformDirection on object B to change that direction to be relative to its own transform, then move it by that direction and distance
Try that and tell me if it works, because that's exactly what I did first and it didn't work because that's not what transform direction does.
that is precisely what TransformDirection does, it changes what would be a local space direction to world space direction. show your code to prove that you actually used it correctly
"Transforms direction from local space to world space." "If the transform has no parent, it is the same as Transform.position."
I deleted it days ago
If there's no parent localSpace and worldSpace are exactly the same.
and if the fucking object is rotated a local direction is not the same as a world direction
Local space does NOT take rotation into account.
It ONLY compares it to the parent's rotation. If there is no parent then it's the same as world rotation. Try it yourself if you don't believe me.
then show the fucking code you tried and prove it doesn't work. i've used TransformDirection countless times to move objects based on their own rotation by giving it a local direction
Did they have parents?
no
I'll rewrite the code, but it's a waste of time.
do it. i would love for you to actually prove me wrong
would you look at that, i was right all along
What's the code on that?
it's literally just using transform.TransformDirection to change that localSpaceDirection vector to be relative to the rotation of the object and adding it to the position
if it doesn't work for you then the issue is your implementation. feel free to ask for help with the code in #💻┃code-beginner
My only guess with what could be going wrong is that this is relating to trying to reposition a vuforia camera and maybe they're doing something unexpected under the hood.
But thank you for proving me wrong.
It actually makes me feel better because that's the very first thing I tried.
this thread gets a big "huh?" from me
Well, thank you very much. My problem isn't solved but at least I have a better idea of where to look for the solution.
what is the big picture thing you are trying to do
vuforia camera is very concerning
I'm trying to move the vuforia camera to match the position and rotation of a physical place using OnStateUpdated.
isn't the point of vuforia cameras that they follow the device position?
what is the idea?
Yes, once it matches the world position then we want it to match device position and rotation.
hmm
but the real camera is where it is
you can place the unity camera wherever you want
So A.) Move to the position. B.) Vuforia moves it back to original position next frame. C.) Read that frame's position and rotation update and apply it to where you were in A.
i see
well what is the even bigger picture idea here
you can give me the Idea of the Idea
because the words you are saying don't make sense
i mean that i believe that you know what you want
but that it is hard to understand what you are really trying to say
you can, naturally, offset the unity camera relative to the AR device position
but
match the position and rotation of a physical place
doesn't make sense to me. i am imagining the Eifel tower, and then, why would you want the camera to be facing the eifel tower's z+, and be positioned in world coordinates all the way in france
but that's what the words
match the position and rotation of a physical place
mean
i'm not trying to be pedantic
are you trying to say you want the user to explore other locations around the world?
in AR?
No it's hard to explain.
is it one of those games where you pretend to be a plant
and you are in a video game level
like you are a prop and you hide
lol
Okay, imagine you're in a parking lot, and we want to align with the parking lot. We know the unity coordinates of every parking space. You put in the parking space then the vuforia camera is placed there and continues to move and work like a vuforia camera should.
okay
wouldn't you align the parking lot, not the other way around?
or am i being stupid
the vuforia camera is wehre it is
i suppose you could rotate the unity camera relative to the vuforia camera, which is so easy that i'm sure you've tried that
but why?
that doesn't make any sense
i assume you mean "align the parking lot such that, when you START your session, you are looking from the center of this parking space and your camera is parallel to the lines" or whatever
We have an existing system that auto-aligns that works for certain situations. That requires everything to be positioned at the world origin, and the camera to be placed relative to it.
hmm
and the idea of the idea is
to practice parking trucks?
to practice being a parking attendant
you ARE a Mazda Miata
and you're actually trying to run people over, in AR
or people jump into you!
I'm under NDA and can't give the actual idea, that's as close as I can come without giving it away.
okay well i have hit my limit. it is really really straightforward, using parent constraints, to adjust the orientation and position of the unity camera relative to the AR position
okay well this wouldn't violate an nda anyway
it sounds like you are a miata with googly eyes
trying to find juicy targets
to run over
it's so straightforward that i am definitely missing something*
probably something to do with how the steering of the miata affects your ability to mow down nimble costco shoppers versus your slower, easier to target cheesesteaks-and-milkshakes crowd that also inhabit parking lots
you can initialize a parent constraint with the miati in the "right position" once the user has at least made their AR camera level. then you will have Aligned to the Parking Lot
@gleaming hatch does that make sense?
experiment with the parent constraint
then you can separately scale the target pedestrians
edy's vehicle physics supports deformations with soft body collisions
I'll play with it and see if I can get it going tomorrow. Thanks for the advice.
do you have any questions about the softbody physics simulations of fat parking lot pedestrians?
Haha
or how to correctly model the consumption of a whole costco chicken and how that will affect the mass and velocity of the target
ugh
🫡
Am I allowed to somehow upload the build onto my Linux based server/VPS after Unity Cloud build is done? I see options to run custom scripts (script hooks) after or/and before build, but since Cloud Build happens on remote Unity side, not sure how I would make it end up via SSH/SFTP onto my own server
you can execute a post build method or shell script
usually you store the artifact somewhere (the cloud build does that already), hit a webhook (cloud build can also do that), and something else pulls the artifact
Hello, I'm trying to serialize a 2-dimenional array. Guess I have to convert into a serializable type. Do you guys have any suggestions which type to use or maybe even alternate solutions?
you can serialize a 2-dimensional array without converting it to anything
when googling I mostly found contradicting statements about that. I tried using the binaryformatter but got empty fields. Even the JsonUtility doesn't do it.
int[,] bla = new int[2, 2];
bla[0, 0] = 1;
bla[0, 1] = 2;
bla[1, 0] = 3;
bla[1, 1] = 4;
Debug.Log(JsonUtility.ToJson(bla));
i meant it's possible to serialize it, not that c# or unity has libraries for it already
but if you make it a jagged array instead (ie int[][] bla) it might work better
with existing libraries
I'm gonna try that, thank you. Do you know of any handy library that can handle common cases like that by any chance?
oh well i meant change it in your code
but if you can't do that then it shouldn't take more than a few lines to convert it yourself
int[][] bla = new int[2][];
bla[0] = new int[2];
bla[1] = new int[2];
bla[0][0] = 1;
bla[0][1] = 2;
bla[1][0] = 3;
bla[1][1] = 4;
Debug.Log(JsonUtility.ToJson(bla));
Doesn't work either unfortunately
oh dang
did you read the jsonutility docs
check what the available options are for arrays
true, but I was wondering if there's something like a best practice
that i cannot speak to unfortunately
probably just doing it manually is the best practice lmao
All good, I'm just gonna write a tiny converter for my cases I guess 😉
it is common knowledge that unity's serializer is not the best
so you may have to do it yourself
well I'm not as knowledgable when it comes to unity/csharp, hence me asking :> But thanks again for the suggestions!
Buffer.BlockCopy will give you a byte[] from any non jagged array which you can then write to a file
any non jagged means multidimensional arrays work?
yes
oh, that sounds nice! Gonna try that, thank you
@calm glen
byte[] bytes = new byte[value.Length * itemLen];
Buffer.BlockCopy(value, 0, bytes, 0, bytes.Length);
where value is the Array and itemLen is the bytes size of the array contents
i.e. int[] -> itemLen ==4
Thank you very much!
remember to cast to Array before using
int[] myintArray;
Array myArray = (Array)myintArray;
thanks for the help!
any idea how I can change the "index" of sprites containing multiple "images" in the programming? I found a lot regarding Animators, but for a simply change this looks oversized
may I ask something about localization here?
Using nested prefabs instead of non-prefab nested children, can reduce scene file size significantly.
I would like to know if it can affect memory ram as well or not
I mean use nested prefabs in the game object hierarchy as much as possible
For example, I have copied a game object 100 times in a scene. It has several nested children.
The scene size is around 200MB
guys , I am a beginner ,can you recommend me a course on udemy or whatever to learn those things(it doesn't look easy so I ask the pro dev) ? https://youtu.be/S36CH4cbW1A
Check out Makans procedural boss animations in Unity! See the epic style boss battles inside Unity and marvel at how awesome it is! :)
➡️Makan Gilani on Twitter: https://twitter.com/Makan_Gilani
➡️80.LV Interview: https://80.lv/articles/animating-beasts-using-the-procedural-way-in-unity/
🎁 Get OVER 160+ Scripts, Projects and premium content on...
this is mostly the result of knowing a lot of fundamentals
I'm working on reimplementing my state machine class so that the 'Step' call of the state returns a generic enum. The desired behaviour is that if i return null, i continue, but if i return an enum, i change to the state which is tied to that enum
but im running into a strange issue with the state interface
public interface iState<TKey>
{
public abstract TKey? Step();
public abstract void Enter();
public abstract void Leave();
}```
Step returns TKey?
public abstract class PlayerStateBase : iState<ePlayerState>
{
public PlayerStateBase(PlayerStateMachine manager)
{
Manager = manager;
Owner = manager.Owner;
Movement = Owner.Movement;
Input = Owner.Input;
Anim = Owner.Anim;
}
public PlayerStateMachine Manager;
public StateMachine<ePlayerState, iState<ePlayerState>> Machine;
public PlayerActor Owner;
public PlayerMovement Movement;
public PlayerActorInput Input;
public Animator Anim;
public PhysicsData Phx => Movement.Phx;
public Vector2 InMove { get => Movement.RawInput; }
public InputAction InJump { get => Input.Player.Jump; }
public InputAction InDodge { get => Input.Player.Dodge; }
public abstract void Enter();
public abstract ePlayerState? Step();
public abstract void Leave();
and PlayerStateBase's step, which implements the step from the interface returns ePlayerState?
when ePlayerState is nullable, i get an error that im not implementing the interface
but when i remove the ?, it works
any idea what could be causing this? ePlayerState needs to be nullable or else i can't return null in my state's Step method
if i understand you correctly your step function is used to change state of the FSM? it is not generally advisable to make transitions part of states because that eliminates most of the benefits you gain from using an FSM as abstraction --> separating flow from state.
conceptually/architectually what you probably need is the notion of a signal or trigger in your FSM
the Step method contains the logic that runs on each frame of a state, so I use it to check the logic required to change states, let me post an example rq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace Player
{
public class State_Stand : PlayerStateBase
{
public State_Stand(PlayerStateMachine manager) : base(manager) { }
public override void Enter() { CommonEnter(true, true, false, Phx.StandFriction, "stand"); }
public override ePlayerState? Step()
{
if (!Movement.FloorCheck()) return ePlayerState.Fall;
if (InJump.WasPressedThisFrame()) return ePlayerState.Jump;
if (InDodge.WasPressedThisFrame()) return ePlayerState.BackDash;
if (InMove == Vector2.zero) return null;
if (InMove.x != 0) return ePlayerState.GroundMove;
else if (InMove.y < 0) return ePlayerState.Crouch;
return null;
}
public override void Leave() { }
}
}
yes, that check logic should not run in the step but be completely separate
I dont think i follow, are you suggesting having a seperate type that handles the logic of changing states, and the state itself just runs whatever code the state needs per frame?
yes
also consider that a FSM does not necessarly have to run every frame in every state
a "tick" or "step" could just be one of many signals you send to it for evaluation
I'm sure you know what you're talking about, but for my purposes at least this is just the more convenient way to handle state logic for me, if the logic that changes state was seperate from the state code itself, the states would virtually all be completely empty and the state change logic itself would be a giant mess. In any case though this is just for a prototype, so if i end up finding some better examples later down the line ill consider it
maybe you want to have a look at this neat FSM library that implements a formal, hierarchical state machine (a unity version (that uses unitask) can be found on open upm) https://github.com/dotnet-state-machine/stateless
in any case though, do you have any idea why that nullable type would cause issues in this way?
sure thing, just when it falls apart you know where to look for reasons and improve it, if its convenient now, keep it
TKey? Step() this means Step return nullable reference type TKey. This has no effect for value types.
You should give where TKey : struct constraint to make compiler recognize TKey? as Nullable<TKey> which is for nullable value type.
Is there a way to yield back and forth between Python for Unity and the editor? Like can I do a while(true) loop in Python, yield back to the editor, create some data, then go back into python and parse the new data?
python is a language, unity is an application, what are you talking about?
Looking for strategy guidance.
I have a turn based multiplayer battle game. I have a battle state class which has.. many many members, nested and otherwise. It implements equality checking (I think IEquatable, I'd have to check). Turns are a series of player actions sent to the server, which calculates and replies with a series of "battle actions" (things that modify the underlying battle object).
Occasionally (like right now) I have a desync bug of some sort that's a pain to chase down. The battle state is represented in several places:
- The server, in memory
- Players "true" copy
- Players "animated" copy (which lags behind the true copy and catches up as animations unspool).
Any thoughts/strategies on how to more effectively debug this class of bugs? Happy to talk through it if you have questions, or give a little video demo if it helps.
a possibility for debugging complex desync issues is to write a hash function that entirely captures the state and compute it between every system operation/update - as soon as it deviates you'll have an immediate response that something isn't identical in the state
Yeah, I mean, I have that in the IEquatable checks. The issue is more.. figuring out when and where something went sideways.
Like, there's ... 5 different player actions, 27 different "battle actions", approaching 60 distinct abilities that all create a different series of battle actions.. if I make a tiny error (and to be fair, I'm getting good at just not) they're very hard to debug.
I was currently (just now) debating serializing the entire battle model and saving it from turn to turn so I could recreate it after the fact and examine it.. but a couple things.. battles tend to run about 50-100 turns, and the serialized byte stream is about 1k. Maybe that's small enough to work with? I'd probably also need to write my own tooling to examine it though..
you have the hash or IEquatable (be sure it's actually capturing everything that constitutes state) and calculate it between every action and ability - as soon as it deviates, it must have been the last action
you don't need to save the entire state, just a hash of it so you can tell if it's not synced
Quick demo of what I'm talking about - server console window is on the left.
I could potentially do a hash and send it along with every turn.. compare it on the client to what it expects, both as it receives it, when the client is done processing it, and on both sides of the animation on the client as well
In the console log, you see things like "this turn contains 6 battle actions" - those are the messages with state changes that it sends to the client.. the client and the server both process these things in parallel.. but yeah, the desync bugs are really tedious to chase down
The other thing to consider is .. we're pretty close to opening this up to beta testers (friends and family, really) and... we're gonna want some easy way for bug reports to come in.. It might be nice to have the tooling and complete battle states saved so we can recreate issues on our end instead of relying on users to tell us what happened
in the case of a turn with 6 battle actions, in my mind you'd have 6 different hash values computed, one after each action - essentially as granular as it can be while separating distinct systems/state changes
as for beta test bug reports, you can take a snapshot of the state after the fact if it's not synced and capture exactly which action caused it too
Anyone has looked into "SSL CA certificate error" when requesting with UWR?
This only happens to very small percentage of my players, and they have old Android devices.
There are plenty forum posts and search results in this Discord, but I'm pretty sure all the answers are wrong:
- "The certificate is actually not valid": I'm using Cloudflare, and the certificate is 100% valid, checked both on PC and obviously it works for everyone else except those small percentage of players; those players can visit the API endpoint in browsers just fine.
- "Those devices don't support TLS 1.3": Cloudflare supports TLS 1.0, 1.1, 1.2, and 1.3. On those devices I asked them to visit the API endpoint in browser (both Chrome and device built-in browser) directly and they all work. Checking their connection it also shows that it's connecting via TLS 1.2, so Cloudflare is also properly handling lower TLS versions.
- "Just change your code accept to any certificate": yeah no, that's throwing away security completely.
The most relevant thing I've found is that Unity 2020's TLS has problems on Android, but apparently that issue has long been fixed, and I'm using Unity 2021.
There are also other people reporting issues here with not just Cloudflare but also big cloud providers like AWS, Azure, etc, so this doesn't seem like a Cloudflare issue either.
Any help would be appreciated.
spellsource stores reproducible traces. it's sort of the best way. you need to store the initial states, the actions taken, the binary versions, and the random seeds
Yeah, I can do that. I just ... sort of am in crunch so didn't want to spend a lot of time on the tooling for reviewing the traces.
I gave my team an estimate of 3 days just for the tooling and feature.. and they sorta groaned
Hey, my issue is still around. I wasn't able to find any fixes. Does anyone know what's wrong with the equations?
Add some logs in each method to see if the refresh is being called properly and if not where it gets stuck. If it calls the method, then it's just an issue with your refresh method.
Hi everyone, I'm trying to do builds with the build pipeline. I get the error
UnityException: Build path contains project built with "Create Visual Studio Solution" option, which is incompatible with current build settings. Consider building your project into an empty directory.
Here is my code.
private static void Build()
{
var buildPlayerOptions = new BuildPlayerOptions
{
scenes = new[]
{
"Assets/Scenes/Bootstrap Scene/Bootstrap Scene.unity",
"Assets/Scenes/Main Menu/MainMenu.unity",
"Assets/Scenes/In Match/InMatch.unity",
"Assets/Scenes/Hybrid Vs Instancing/GPUI Multi-Components.unity",
"Assets/Scenes/Hybrid Vs Instancing/GPUI Multi-Components/Physics Simulation Sub Scene.unity",
"Assets/Scenes/Hybrid Vs Instancing/GPUI Multi-Components/Presentation Sub Scene.unity",
"Assets/Scenes/Hybrid Vs Instancing/GPUI Multi-Components/Simulation Sub Scene.unity"
},
locationPathName = "Release",
target = BuildTarget.StandaloneWindows64,
options = BuildOptions.None
};
var report = BuildPipeline.BuildPlayer(buildPlayerOptions);
var summary = report.summary;
if (summary.result == BuildResult.Succeeded)
{
Debug.Log("Build succeeded: " + summary.totalSize + " bytes");
}
if (summary.result == BuildResult.Failed)
{
Debug.LogError("Build failed");
}
}```
I suspect that locationPathName is incorrectly formatted.
But according to the docs it should be correct
https://docs.unity3d.com/ScriptReference/BuildPipeline.BuildPlayer.html
Any ideas?
buildPlayerOptions.locationPathName = "WindowsProdBuild/myProject.exe";
Results in
Thank you!
Bad documentation.
buildPlayerOptions.locationPathName is expecting a file name.
To get a meaningful error message where it says this try using
locationPathName = "Release/",
Trying to use Reflection to get a method from a class using a custom editor class. However, I'm getting AmbiguousMatchException because there are two methods with the same name (one with parameter, another without. I want the one without parameter). Any tips how to filter to get the method without parameters?
You cna pass a parameters array that's empty
I am using Types.EmptyTypes
{target.GetType().BaseType.GetMethod("Foo", System.Type.EmptyTypes).Invoke(target, new object[0]);}```
That's what I'm trying
Error is "AmbiguousMatchException: Ambiguous match found."
the class has:
public void foo(); // <--- trying to get this one
public void foo(T value);
Hey! Anyone knows about Unity's VirtualFileSystem and how it works? I'd like to check out some material on it, but I can barely find anything online, I would love to read up on it tho
what are you trying to do
why do you need to use reflection here
Sorry I am late. Yeah I am stuck at figuring out how exactly to pull that artifact towards my server. Maybe some sort of linux cron? but how do I access my cloud build artifacts off CLI anyway
you can generate the cli from https://build-artifact-api.cloud.unity3d.com/api/v1/api.json using swagger or simply curl
Ah cool. So I need "GET /projects/{projectupid}/buildtargets/{buildtargetid}/builds/{number}/artifacts" call? And download the latest one. Is there way to trigger check post-successful build instead?
so I dont have to use cron or something to redownload same thing potentially
I want to have my Mirror headless server updated live every main branch commit basically
As far as I know, python doesn't support coroutines or async-await.
Python has concept of both yield and async/await
ah, you're right. It was added in v3.5, however, Python for Unity is v2.7.5, I believe.
Ah I see, I thought the question was about IronPython, didn't know there was dedicated package for that.
Trying to call the function of a generic class (template) on the editor.
I know I can fix it changing the name of the function, but I would rather have them with the same name and different parameters
Check if you also have static method of same name? What binding flags are you using?
Or do you have same signature method with new keyword , etc.
I only have public void foo() and public void foo(T value) with the same name, and I'm using no binding flags since I thought it could be identified by the number of arguments.
there is no signature method with new
hi guys, im trying to get this loop to wait each time for a new gridposition but i cant seem to get it working at all
i think i need to get all the gridposition tasks into a list/array then wait for the to be donethen iterate through the gridpositions after that and spawn everything?
foreach (var unitData in unitDatas)
{
Vector3 unitSpawnWorldPos = LevelGrid.Instance.GetWorldPosition(await GetGridPosForUnitSpawn());
Debug.Log("getting grid pos ");
await Task.Delay(2000); // why is this needed to get the intended behaviour??? without this this loop executes instantlly and all units spawn on the same location
GameObject unitGameObject = Instantiate(enemyUnitPrefab, unitSpawnWorldPos, Quaternion.identity);
unitGameObject.GetComponent<Unit>();
Unit unit = unitGameObject.GetComponent<Unit>();
unit.SetUnitName(unitData.unitName);
}
*edit
i got the behavior i want but... see my comment in the code, so strange
Guys is the migration to .net 7(or later) still under progress or is it abandoned.
I searched in unity roadmap but haven't found it.
Check the forums for the latest news
I have problem with canvas and screen size.
My screen size is 946x532
My canvas size is 1920x1080
My UI image is 300x200
Mouse input returns value base on SCREEN SIZE, so up to 946x532
Problem is i want to position image at mouse position + its height (200)
If i use transform.position, problem is with getting image height which reports 200 but actually because of screen size it should be less (about 100)
If i use RectTransform.anchoredPosition, image again is not properly positioned since mouse input is based on screen size and not canvas size
I could use some hack of calculating ratio screen to canvas and multiply with mouse position or something but is there a cleaner way?
actual size of image on screen? Convert mouse position to canvas size?
this happens if i offset it by RectTransform.rect.height of image (panel with stats)
image should be next to elf (follows mouse)
Might find the answer in this video: https://www.youtube.com/watch?v=YUIohCXt_pc
OHH thanks, ill check this
any idea how you can import a MySQL client to unity? requiring the package using nuget ends with dependency errors, as they need different versions of the package I cannot place it manually
why though? what are you trying to do?
How do i make an object slippy ? I know that we need to assign the physics material to its collider... HOWEVER it does not work.
I wanna simulate an airhockey table.
My table is a cube, its box collider has a physic mat with all set to zero ( so it should be slippy ). My pug is a cube with multiple colliders, however when i drop it on the table its not... slippy... when i throw the pug at it, it almost stops directly. I wanna make it like ice basically.
Any ideas ?
maybe use an asset store package
I'm using the NuGet Packagemanager Asset, a mysql package is not available as far as I saw
Well generally it's also considered very bad practice to connect to a mysql database from your game
it's a multiplayer game using mirror, and only the server should connect by mysql to the states database
You also didn't search very hard
I searched the package manager, its showing different results?
Anyways, if you want to include a nuget package then you have to include all dependencies and resolve all conflicts
Chances are you have to disable validation for versions to prevent conflicts but that's risky af
Package manager != asset store
oh I can do that?
i think you should use an asset store package
you are way out of your depth here
maybe ask #archived-code-general #💻┃code-beginner
you can try changing the name of the function, i don't think that resolves the issue
you aren't using the Reflection API correctly
this isn't going to resolve your issue
the most robust thing is to have something that checks every minute for new artifacts
you can use a webhook to reduce this time to below a minute
but i don't think the savings is worth the massive increase in complexity
Playing around with AR and the hololens.
Wanna create a airhockey table with a sliding pug.
Added physic materials to the table and a rigidbody to the pug... set friction to zero.
Pug does NOT slide...
Why ? Any ideas ?
Hmm Try using GetMethods instead and figure out what are ambiguous matches?
I fixed already, basically added a base class without template, then did the call without using reflection
the function I wanted didn't use template types, so it was fine
right... that makes more sense
but what are you trying to do? static methods that belong to classes with generic signatures are best declared protected or lower
What I wanted was to add a simple button on editor to activate a function in a template class, but apparently I didn't do it correctly
is that relevant?
okay well i thought i could help you model this better
it's the root cause of your problem
whatever it is you are doing*
It's fixed, I just wanted to know how to do with reflection because it might be useful
I tried in c# pure and it worked, but in unity it was giving error
It’s called generic in C# - different from template
Sorry 🙂
it sounds like you tried something in C++
anyway we're just trying to help you
usually using generic signature abstract base classes for non-collections is a mistake
I have a SO derived class that is generic, so it accepts arguments of multiple types (GameObject and several others). They had a function foo() and another foo(T value), but I couldn't reach the foo() on the custom inspector.
"Generics are meant for collections, including of possibly 1 item"
SO derived class that is generic
well... this is going to make your life really hard
class xyz<T> : ScriptableObject
yeah
anyway, since foo didn't use the generic type, I just made another base non-generic class and inherited from that instead (similar to a interface)
then it was reachable
i'm refining how to express the limitations of generics. they should be used for Collection<T> and Single<T> / Result<T> { Exception ex; T value} and things that look like that
but what ARE those things? collections and... collections of a single value?
like a Tuple<T1, T2> is a collection of 2 values, that makes sense. but how do you differentiate between Result<T> and AbstractBaseWeapon<T> : MonoBehaviour where T : AbstractBaseWeapon<T>
they look different because i exaggerated it a bit, but they are sort of th esame
@jolly token another perspective is that Result<T> is pretty radioactive
and really you should never do stuff like that
so maybe generics are only for collections
It is a simple collection of values that send signals to observers any time a value from the collection is changed, nothing special
the editor tool is just for debugging
hmm
Did you mean "UniRx"?
anyway i don't wanna bully you on this. there are pre-existing libraries that achieve these goals
you should try
Thanks
none of the reasons in the readme are good arguments
Pray give a better argument then 😄
Reason 1. They are mean (sic) to be used as Data Asset
Yes, Scriptableobjects are meant to be data.
Data is mutable.
The biggest problem with Scriptable Objects is that whilst they are mutable in the Editor they are not mutable at runtime.
Reason 2. You can do it with any C# Object
No you cannot. There is no facility in Unity to turn any C# Object into an asset
Reason 3. Don't bind yourself with Unity Inspector
The use of the Unity Inspector as a means of making references to other objects is a Unity standard. It stops you having to use .Find and .GetComponent unnecessarily.
Reason 4. It makes your project Unmaintainable
No more so than any other badly designed project. ScriptableObjects are not inherently 'unmaintainable' any more so than e.g. Monobehaviours.
Reason 5. It lacks of Expandability
As standard, no more so than Monobehaviours
Reason 6. There is (sic) ton of better Alternatives
What to these have to do with data containers?
Reason 7. You cannot turn off Domain/Scene Reload
Really?
Conclusion
OK, you dont like ScriptableObjects, I get it. But this is just nonsense. Use a Spreadsheet? Get real.
You don't even get the point of the repo and don't seem to know what Scriptable Object architecture is 😂
I suggest you check my publishers page on the asset store before making stupid statements
Whatever you published it does not change the fact that your statements are totally missing the point lol
The biggest problem with Scriptable Objects is that whilst they are mutable in the Editor they are not mutable at runtime.
This is not true at all, it is still mutable at runtime and that's the point of so-called SOA. You should say "They do not persist in the build"
you disagree with me, you see my standpoint, so publish a rebuttal.
I disagree with your standpoint and my reasons are stated above.
However I do not think this is a suitable topic on this discord in this channel
I don't want to be mean, but observer is just a pattern. All patterns have pros and cons, and they are not supposed to be used alone in a project. You can always use alternatives to fix the cons of a pattern if the benefits are too big to pass
I think the question of "SOA vs Anti-SOA" is kind of meaningless, since it depends a lot on where they are pplied
the discussion is code based, and fairly advanced with the nature, i feel its appropiate
There is no facility in Unity to turn any C# Object into an asset
This also means you are completely missing the point 😄 This ain't about using SO as data asset.
The use of the Unity Inspector as a means of making references to other objects is a Unity standard.
That does not mean you should assign everything from inspector.
What to these have to do with data containers?
I'm not talking about data containers if you understand my intention correctly
Others are also defending for 'general SO asset' not about 'SOA'
I guess a better discussion would be "where should we apply the observer pattern, and where we shouldn't"
Arguing the toss about design paradigms is better suited to a philosophy channel
It's not about observer pattern 🤔 You can always implement observer with C# classes
You can make a game without Unity
Observer pattern is innocent in this discussion
I'd be question for any other 'design pattern' to be in ScriptableObject
Because they are data/asset, not logic or code component.
I agree with your point that the main use of scriptable object is to have a shared container for data, but if someone finds a way to make their life easier by using SO, I don't see a problem about that.
In fact, if you follow a DDD paradigm, ScriptableObjets become invaluable
🍿
Sure, but I would have problem if anyone uses this "SOA" or any other anti-patterns like singleton, public fields, etc because they think it makes their life easy. I think it's worth to discuss why it's bad and should be avoided.
Are you still talking about "SO as data asset"? No one said using it as pure data asset is bad, other than being unable to mass-edit.
why do I get the impression that you have had a bad experience with a SO implementation and have decided to throw the baby out with the bath water?
Because you're not understanding the conversation correctly 😄
I understand perfectly, I think the problem lies in you not understanding how to implement SOA properly
Say what is SOA then. Since you're the one said "What to these have to do with data containers?".. How is SOA "data containers"?
in my experience, as soon as you have a large (>10) collection of scriptable objects, even strictly as data assets, it is clunky
Agreed, SO's are a very blunt tool. But, unfortunately, they are the only 'built in' tool we have to work with
i like to use them this way
// rare, maybe 2 copies of these in your project
// used to recreate UI styles for UGUI
public class RareUIStyling : ScriptableObject {
public Color highlight;
public Color unselected;
}
// otherwise, big localizable thing
public class ConstantLocalizedGameDataObject : ScriptableObject {
public ConstantLocalizedGameData gameData;
}
[Serializable] public class ConstantLocalizedGameData {
...
}
SOA is so bad
you can create an observer this way
using UniRx;
using UnityEngine;
public class GameController : MonoBehaviour {
private ReactiveProperty<GameData> m_GameData = new();
public IReadOnlyReactiveProperty<GameData> gameData => m_GameData;
public static GameController instance { get; private set; }
void Awake() {
instance = this;
}
// other code calls this with
// GameController.instance.DrawACard();
public void DrawACard() {
var gameData = m_GameData.Value.Copy();
var nextCard = gameData.RemoveAt(0);
gameData.Hand.Add(nextCard);
m_GameData.Value = gameData;
}
}
public struct GameData {
...
public GameData Copy() { ... }
}
that's it.
this encompasses 100% of the functionality of "observer" and "scriptable object architecture", and provides 10,000% more @harsh current
it's the right tool for that job
there is a lot of knowledge in that snippet:
- most valuable game logic is coupled.
- it takes 3 lines to implement a singleton correctly, and no more.
- ultimately, your game data must be passed by value (should be declared a struct), because the only valid reference to it is
GameController.instance.gameData - UniRx provides all the observe/subscribe functionality you need, including reactive properties.
- you should only "mutate" (i.e., replace game data) in one place, and ensure the rules are followed with access modifiers
i am not a unity content creator, i'm not going to grow a beard and make a whole 600 minute youtube video series about this. but i'm also not wrong
@harsh current does this make sense?
SO are overrated but i'm using it as a data container for static stuff for different units, e.g. max health or sprite ref
this is a misconception. you always end up reinventing prefabs
it would have been better to declare one prefab per unit in your tower defense game - this is, for example, how Bloons TD 6 is architected. probably every shipping, popular game at least
that's why in my experience, i extremely rarely use scriptable objects
the real reason people use them is because they like the comfort of certain UI patterns
making everything Assets icon-and-inspector UI driven is negative ROI
not for any other holistic or engineering reason
You can use ReactiveProperty on SO. I don't see why someone would discard the entire concept of SO just because there are other alternatives.
you can, of course, make a prefab, which has a ui
there is no Return on Investment from replacing a game object in your scene with a component, which is familiar to everyone and robust in its rules, with a scriptable object that has more gotchas
you are advocating for "use scriptable objects instead of singleton monobehaviors," which in my experience is always a bad (negative ROI) option
I read issue you made here https://github.com/cathei/AntiScriptableObjectArchitecture/issues/4
And you also don't seem to understand what is the repo is about.
and suddenly, everything that cathei wrote in that github, is indeed the most relevant
another reason this keeps coming up is that those stupid Unity produced videos really clicked for people
even though what they are advocating for is kind of stupid
@crude granite i cannot comprehend why Unity keeps those Scriptable Object Architecture videos up. i understand they get a lot of engagement, but they advocate for a 200% wrong design. they are like a political conspiracy video version of programming content - lots of engagement, negative value substance
You are just assuming that people only use SO because of a popular video, but SO is just a monobehavior that doesn't belong to an object
it has its uses
i am just saying that i have thought about this a lot more than you, and i'm more motivated than anyone to adopt and advocate for good engineering practices
i am trying to get you to thrive
i don't buy into Content Creation at all - it's not even that one popular video i wish would go away lol
would be fun to watch a channel about grumpy programmer on a holy mission to purge the bad practices
lol
#holy-war
they should mark Scriptable Object as deprecated, and adopt a mature IDL like the protobuf spec to replace its best use case. it was a mistake, in DOTS, to not build around an IDL
magic onion is very close. you just can't build something big or mature around a spec in a C# class. they're too flexible
Cysharp seems to make lots of innovative stuffs for Unity
same thing i said in the issue i created on the repository, i guess most people agree with all of that
one thing i agree is that the video about scriptable objects really messed up people's head and they are trying to use it everywhere, even when there's better solutions that doesn't uses them
Because the statements are totally irrelevant to the repo. It's similar to when one says "Using plane for terrorism is bad" then other says "Why do you hating planes? They are useful for transporting people"
lol, a colorful example
good thing you are not forced to use it
I also think smart pointers are better than traditional pointers, but it's not like I will tell everyone to switch to them. There are instances where traditional pointers might be a better choice, even if the difference is not that big.
some people just like the convenience of having serialization as built in, or some other features that come with SO
if there was a better alternative that was better in all aspects, people would use it
fine line between entertainment and cringe there 😛
there's no line between cringe and entertainment, just take a look at tiktok
for real though, you need to make a channel. you have the talent.
Thanks for the compliment ⚖️ 😇 ⚔️
this is a very Content Creator perspective
another perspective is, the reason there are still new C++ programs written today is because those programmers are a lot cheaper than programmer for better alternatives, not for any good engineering reason
like let's say i made SOA illegal. i'm not exactly sure who would complain. if i made C++ illegal to use for new things, for every 1 person who complains about pointers, there would be 99 more who complain that suddenly, their cheap programmers are unusable
if there were a programming language government, it would be pretty funny
but a prefab has serialization built in
you can attach a component to a prefab, and have a bunch of prefabs in your Assets/ folder
it's like there's some mental block to use prefabs. it's inexplicable
unless... because unity didn't release "Prefab Architecture"
that invoked all this woo
here's the thing @harsh current , the kind of person who
can't handle like, create a prefab, then attaching the right component to it
and that's the 1 component
like a Unit component or whatever
then filling in the fields. this is the same thing as a scriptable object, as you've described it
the kind of person who can't handle that, isnt' going to be able to make scriptable objects either
they are hopelessly dumb. which isn't a real person anyway. nobody is that dumb
But monobehaviours are different from scriptable objects in essence
Go prefab architecture, it even has components and variants, you don't even have to make CreateAssetMenu lol
that's true... but every single thing you want from scriptable objects you have to add on, which gives you monobehaviors at the end
everyone ends up reinventing monobehaviors with their scriptableobjects
"oh, how do i add lifecycle?"
there are only a few root causes to this disease
(1) people who watch that video. honestly they are the easiest to convince
(2) people who have a very, very limited knowledge of the unity api, and try to use scenes, and did not discover DontDestroyOnLoad.
(3) people who gain most of their programing knowledge from content creators. i find this audience the hardest to convince
And which one am I?
there are PERCEIVED causes, like "(4) what about people who need UI, like artists, to make game content?"
i mean, those people don't exist. there is nobody so stupid as to screw up attaching a component to a prefab. it's offensive.
nobody is going to screw that up
and besides, it's a UI anyway
@undone coral There is one huge flaw in your argument, you cannot transfer a monobehaviour from one gameobject to another
i can transfer a prefab
there's so much enthusiasm for avoiding code, or making glorious editor UIs, for an audience of 0
a big part of this journey, this rejecting SOA journey, is accepting that Unity - really, all game development - has no audience of people who stubbornly refuse to learn the basics of programming. that is an actually extremely small amount of people! almost everyone i know with decent art skills - for example - is not hostile to excited to learn things, if that's someone you want to have access to your unity project for some reason
to clarify i mean, wherever you would have a scriptable object in your assets folder, like defining a tower defense tower, you woul dhave a prefab instead
you can of course reference that prefab in many places
You are adding an unnecessary overhead and some rework just because you don't like SO
i don't know, i'm not trying to bully you, but to illustrate that it's not really about SOA
I get what you mean and it is a valid design principle, but why when a ScriptableObject does the same
look at these generics you are writing. you are adding the overhead already
you are reinventing things
because you wind up reinventing prefabs anyway
in order to get something useful out of, i wrote a scriptable object for every tower in my tower defense game
you wind up reinventing prefabs
you wind up specifying a collection of behaviors with a lowercase b inside the scriptable object
Well, no point arguing if you think there is zero advantage in SO.
then instantiating multiple objects or GameObjects, ultimately, at runtime, if not for rendering then for some decoupled-but-actually-coupled game logic
I won't bully you
at least in every codebase i've ever seen
No, you end up reinventing Scriptable Objects.
I have limited prefabs with plug in behaviour
well...
