#archived-code-advanced
1 messages ยท Page 160 of 1
i need an object's sorting layer or depth or something
can a box collider 2d detect multiple collisions?
if they are all at the same distance, then there is concept of "a closest one"
RaycastAll
if you use collision/trigger callbacks you get one callback for each other collider, so you would have to keep a list manually over multiple such callbacks to have a list of all collisions that occur inside one update... that is not an elegant way to do it, so better use a raycast.
How would I go about creating a component input in the inspector with a editor script. I want to have an input that references another gameobject component but with the GUILayout or EditorGUILayout?
@compact ingot ?
I figured it out actually. It was ObjectField
I'd throw that code away immediately and rethink the whole system based on what was described by me and others above. Also read the docs on raycasting and various methods on how to reference other gameobjects such that you don't have to use .Find
Or if you do use Find, it's in Start, and not on every collision
can we store in json or scriptable object refereces to scene object using local identifier in file from scene files?
like hook up into serialization during loading game save, and store reference to monobehaviour using this LocalIdentifier from scene file
only if you build a resolving mechanism yourself, you could maybe generate an ID of a GameObject that is based on a GUID and the the scene name and store that on the SO.
Another approach is to make prefab of those gameobjects, reference them to scriptable object, and then reference that one scriptable object to scene using another gameobject and a script.
Its like beating the bush, but gets your thing done
It's something I'll have to solve eventually too. When my procgen plants items, it will need to ID them. Then a save file can regenerate the level based on the saved seed, and regenerate the same items with the same IDs, but then also remove the already picked up ones based on ID
my problem is to save randomly generated quests, and those quests can reference scene characters' objects
if there was some unity method to get object from scene from its Local Identifier in file, but it needs to work on build
You'll need a way to generate an ID for scene objects that will ensure the ID never changes when you reload/replay the scene
yeah, well i can serialize my own guids, but i was hoping for some built-in solution ๐
The simple way, but prone to user error, is to have a string on the object that is its ID. If you don't have many scene objects to track, this might work fine. As long as you never accidentally reuse the same ID, you're good.
If you have a lot, or you're using procgen, you'll need some algorithm that generates the ID in a reproducible way
Unfortunately no built-in unity method for it. Probably to dodge painting devs into a corner with a setup that only works for some use cases
@flint wind so basically if you have to reference scene files from SO or json save files you need your custom ID system? ๐ฆ
Essentially. But there's many others who have tackled this, so google searching should turn up tutorials and other peoples' articles on the matter.
Part of the reason is that Unity's own gameobject ID system is not guaranteed to replicate the exact same way for everyone. For you, the number is 8345789, and might always be that, but someone else playing gets 190286563
yeah, but there is a difference between instance ID of every UnityEngine.Object and LocalIdentifierInFile. instance ID differs among computers, playmode sessions, scenes loaded but local identifier is serialized in any asset files to keep references within them.
so creating custom id system seems like doing the same thing in parallel :\
Hi, I'm trying to make a server side movement validation to reduce possible speedhack in my game but I'm facing a wierd problem. Every fixedUpdate, the client calculates his position and then send it to the server with the inputs. The problem is that the server doesn't receive every ServerRpc calls. Could it be due to lost packets ? Cause I really don't know why the client calling the movement function but not the ServerRpc one. Here's a little part of my code
edit : the client is calling the serverRpc but the client still manage to move faster than the server cause it's missing frames
You probably need to look into some solutions for call/verify behaviour with the server
Basically, the client sends the input, but does not process it until the server replies. This will however effectively mess up real-time responsiveness
unless you assume it is valid and only react to the server responding to say something is invalid. Do you need to know if each input is valid or could you get by with only knowing 1 in X? If so then its not a big deal if some responses don't come back
Also, this is just brainstorming. I have not done this myself, so this is just me spitballing ideas
im having trouble with aiming in my game it should work but for some reason it wont https://gdl.space/qekowayete.cs
line 129 + correct, it should work
To have a good feeling with movement, the client is making the movement by itself and then it send the inputs to the server. Then, the server have the same code and at the end, if the Vector3.Distance between the transform.position and the one from the client is less than 0.01f, the movement is right and it doesn't respond to the client since it's already to the correct position. The problem is that sometimes (idk why), the client moves to the next frame but the server just don't get the update. So for the next frame that pass to the server, the deltaPosition is ok but the client and server haven't start at the same place. sorry if it's confusing
@idle bridge what network solution are you using?
Mlapi
and photon realtime for the transport
cant help with that :\ all i know is that Photon Bolt has good online tutorial for client side prediction with server authorization (basically what youve described)
https://doc.photonengine.com/zh-cn/bolt/current/demos-and-tutorials/advanced-tutorial/chapter-3
Networking middleware for Unity 3D and realtime multiplayer games and applications. Get started without having to know the details of networking or write any complex networking code.
ok thank you ๐
I will follow this topic here though, cause it always bothered me, what happens to lost udp packages when youre using client side prediction ;D should they be re-sent if they got lost or what
the transport handles that (what happens with lost packages)
I have no idea why the ServerRpc doesn't get call then
if its causes by lost packages you'd get inconsistent behaviour, seems you get a consistent error though
not really
it's inconsistent...
then it can be lost packages, a race condition or maybe thresholds that are too tight
ho
Is a fixedUpdate of 64 frames/s too high? like the server framerate is 64
at the same time it should work? I'm so lost xd
fixedupdate is independent of update
Yeah, all the code is in fixedUpdate for now
if they are both the same there is no guarantee that they are interleaved perfectly
it's why idk why frames are missing since it's suppose the call server every time
how do you test if the RPC is received by the server?
I debug.Log the position the client predicted and the server predicted and after a little time, the positions starts to be.. like not in order. The client goes faster. The server can't handle missing frames cause the deltatime is always the same. so it can't adjust
maybe you need a more complex prediction algorithm?
I don't use rigidbody bc of this. I looked everywhere and the movement always return a position without a lot of changes everytime
I have an custom EDITOR script that allows me to add a gameobject ( A ) to a list ( "gameobjects" ) in another game object ( B ). However, when I press play, the "gameobjects" list becomes empty. Why is this and how do I fix this?
do you have a bit of code to show?
is the list a serializable field, did you mark the list as dirty after change and did you save the scene or prefab it is a part of? If the editor script uses the SerializedProperty API, this is all taken care of, if not, you may have to do it manually.
Hmm, let me think for a moment
WOW I just wrote this whole thing and discord took it down
I wrote out the code
ok give me a sec
I am going to have to paste it in without it looking like colored code
```cs
// your code here
```
You need to post multi-line codeblocks using the instructions in #854851968446365696
I did that and it deleted it
I don't think you did
You must have used single-line `...` for a multi-line block.
those are ` not '
oh i see, I just clicked discords <> button
but how yall know what I did cause its gone for me?
the whole message is gone
you are not the first
Ok imma give this another try
//DroneComponent Script
public class DroneComponent : MonoBehaviour
{
[HideInInspector] public DroneComponentManager manager;
public void LinkToManager(DroneComponentManager manager)
{
if(this.manager != null)
{
this.manager.components.Remove(this);
}
this.manager = manager;
if(manager != null)
{
manager.components.Add(this);
}
}
}
//DroneComponentManager Script
public class DroneComponentManager : MonoBehaviour
{
public List<DroneComponent> components = new List<DroneComponent>();
}
//DroneComponentEditor Script
[CustomEditor(typeof(DroneComponent), true)]
public class DroneComponentEditor : Editor
{
public DroneComponentManager manager;
public override void OnInspectorGUI()
DroneComponent myDroneComponent = (DroneComponent)target;
var manager = (DroneComponentManager)EditorGUILayout.ObjectField("Link Manager", myDroneComponent.manager, typeof(DroneComponentManager));
if (manager != myDroneComponent.manager)
{
this.manager = manager;
myDroneComponent.LinkToManager(manager);
}
base.OnInspectorGUI();
}
}
The comments are separating what class they are coming from
actually let me just add that
so in the drone component editor script, i check to see if the "Link Manager" object field is changed from previous
if so then run the LinkToManager method in myDroneComponent
If you mean either manager or something you do in LinkToManager is not persisting, then you need to either use Undo, SerializedObject, or SetDirty.
This is a topic for #โ๏ธโeditor-extensions, where that is pinned
on the target object
I'm creating UI elements at runtime, and assigning on click events to Buttons.
For some reason, it seems as though the newly created elements only ever call the OnClick method on the first button that was created.
I've scoured through for hours, even refactored a few times and I can't seem to solve this issue.
Is anybody able to take a look with me?
GameObject CreateNewStatLeaderboard(string type, List<LeaderboardEntry> leaderboard)
{
GameObject list = Instantiate(statList.gameObject, statParent.transform);
list.name = "LIST - " + type;
UnfoldList myList = list.transform.GetChild(0).gameObject.AddComponent<UnfoldList>();
list.transform.GetChild(0).GetComponent<Button>().onClick.AddListener(myList.TogglePanel); // += myList.TogglePanel;
myList.Setup();
list.SetActive(true);
CustomiseStatList(list.transform, type);
It's extremely straightforward stuff
Just isn't functioning at all how I'd expect it to
setdirty didnt do anything, I dont think I want to do undo, and serialized object didnt do anything
To be clear, the list that I am adding to does seem to get added to, I see it go from 0 to 1, but when I press play it goes back to 0
Yes, it is transient if the serialized object that owns that data is not dirtied
transient?
oh well I know what the word meant lol, I wasn't sure if it was a unity term though
you're very fast with links and images btw lol
but yeah the problem persists
maybe you should try actually doing what was suggested as solution
...? I did
at least linking to some updated code
to my knowlege
Probably worth moving to #โ๏ธโeditor-extensions too
ok ill move it to there and update show the updated code
anyone know how to render a mesh with drawmeshnow using the gameobject layers? I am using a feature in URP to render out all ovjects in this layer infront of everything else. But I need that to work with drawmeshnow. Anyone know how I might do that?
DrawMeshNow doesn't use layers. It literally just draws the mesh, right away.
Hence the name
right, but is there any way to get the effect I am looking for
Other methods like Graphics.DrawMesh have nicer integration into the render pipeline
Does anyone have thoughts on (H)FSMs + BTs?
@hoary crater @compact ingot I found why the serverRpc wasn't working... I feel really stupid xd
I was doing a simulation to go back at client time to make the movement and then validates it, but the simulation wasn't saving the correct tick so, sometimes, nothing was saved for a tick. I found that I made a return in this case... I'm really sorry and thank you for your help ๐
by returning, the server wasn't changing his position but the client was
if (!FramesData.ContainsKey(key1) || !FramesData.ContainsKey(key2)) { return; }
I don't even know how I didn't realised that before...
I've been running into a netcode error and traced it to a possible line change that cna fix it. problem is it's in a script in a package. and when I change it it just changes back when "reloading" unity, is there a way to make this fix stay?
issue lies with GetComponentInParent and want to change to GetComponent
this is the script i can access by clicking on it, and the fix is in a script of the same name except in library/packagecache/com.unity.netcode.gameobjects@1.0.0-pre4/runtime/core/networkbheaviour.cs
let me rephrase that since it was confusing. second screenshot is from what i can access by clicking on the script and the first screenshot is the code excerpt in the packagecache
I am unable to modify this for Cinemachine Virtual Camera. Can someone help?
using Cinemachine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Made for an individual camera
public class CameraScript : MonoBehaviour
{
public float mouseSensitivity=10;
public float distFromTarget;
public Vector2 pitchRange = new Vector2(0,25);
[SerializeField]
Transform target;
[SerializeField]
float cameraHeight;
public float rotationSmoothTime=1.2f;
Vector3 rotationSmoothVelocity;
Vector3 currentRotation;
float yaw;
float pitch;
void LateUpdate()
{
//Setting up basic mouse
yaw+=Input.GetAxis("Mouse X")*mouseSensitivity;
pitch-=Input.GetAxis("Mouse Y")*mouseSensitivity;
pitch=Mathf.Clamp(pitch, pitchRange.x, pitchRange.y);
currentRotation=Vector3.SmoothDamp(currentRotation, new Vector3 (pitch,yaw), ref rotationSmoothVelocity, rotationSmoothTime);
transform.eulerAngles=currentRotation;
//Focus camera on target
transform.position=target.position-transform.forward*distFromTarget;
transform.position+=new Vector3(0f,cameraHeight,0f);
}
}```
photon scorboard system : guys how can I understand who killed who and increase the kill number of character , I handled death but for kill I can not figure it out , here is my code : https://forum.photonengine.com/discussion/19488/fps-game-scorboard-implementation#latest
You need an identification for each player (preferably not strings)
When someone dies send the Event for kill with data of player who killed and who got killed
How can I do identification for each player sir ?
Generate a GUID for each player, or use their photon user name which is unique
Open it in a code editor?
I have a function that creates randomized platforms from individual "blocks".
Is there any way to have the blocks next to each other be "Stiched up" into 1 collider? while the rest remain their own collider?
I have tried to have individual box colliders. However sometimes my character gets "stuck" due to the collider beneath
i have used compositecollider, but that makes the platforms that are not sticking to each other under the same collider
No way to automatically stitch, maybe you could use a Tilemap Collider & Grid to do the work for you. If not you'll have to manually merge colliders
well i am not planning to do manually, because im making a random platform generator for the game
does tilemap and grid stich them up? making them like 3 different colliders, that is fine
as long as the entire thing is not treated as one, or treated as many single blocks
how are tilemap colliders different than boxcollider2d though
Manually shouldn't be that hard if it's aligned to a grid. Just go row by row, left to right. Find first block, keep looking to the right for empty space, when you find it make a box encapsulating the first and last block. Repeat until row complete.
They support merging adjacent colliders
uhm, it's not about manually making the colliders. I'm trying to generate a spleunky type map.
are you perhaps referring to compositeCollider2D with tilemap colliders?
Yes I think this is the one
well this is the one that is preventing what i am trying to achieve though
because using composite, the above platforms will be treated as 1
and it will be hard to "extract" each corner of the collider
Can you show an image of what you mean with "the above platforms will be treated as 1", because from my understanding this is what you want?
sure, here is my current code and a short video
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
basically, i extract the information of the "composite collider" for the coordinates of the corners. And once the character's feet does not detect ground, it will "snap/teleport" to the corner (hence the distance comparison code). to do a rotation, then continue moving.
so essentially, if i use composite colliders, all 3 of the platforms are " grouped" together, instead of being 3 separate individual platforms
composite collider 2d , could work, but i have to find another way to "snap" into corners
yeah I see your problem. The Tilemap & Tilemap collider & composite collider 2d makes it so that a platform is turned to one collider, meaning multiple disconnected platforms are all treated as their own single colliders
But if you end up using that you'll have to figure out the corner problem like you mentioned
yeah. that's right
the problem is if i use the raycast, to detect ground, it will go past the corner before starting to rotate
which creates a gap depending on the speed of the character
If your character is inside a grid you could probably also use the grid to see if a cell has a collider in it
err
Tilemap & grid
currently im not using any tilemaps
Yeah I know, I meant in case you end up changing
this was the problem i was facing using individual box colliders
https://streamable.com/dbev5m
You can still use a raycast though, use a shaped raycast instead of a single ray
i have used circleoverlap, circle cast before, those are not really the best as they create a weird interaction
in the above video, you can see how it cant move past 3 blocks, at least not until the character turns around, rotate once and back again
Hi, I'd liket o negate effects of Time.timeScale on my jump and nobody in #archived-code-general or #๐ปโcode-beginner was able to help me:
private void doJump()
{
rigidbodyComponent.AddForce((Vector3.up * (jumpVelocity)) / Time.timeScale, ForceMode.VelocityChange);
}
The problem is I just fly up in the air when the time is slowed down and I jump
what do you want to happen if timeScale is 0, or do you mean for only > 1 values?
let me try
no it was more of a design question
well it's set to 0.25 now
I'd like to have something like a speedster player class that can slow down time but it doesn't affect him so I did it for left-right movement but I am having some trouble with jump
you don't do that via timescale
here is what I did for left-right movement:
//Better Movement
rigidbodyComponent.velocity = (new Vector3(movingDirection * horizontalPlayerVelocity, rigidbodyComponent.velocity.y, 0))/Time.timeScale;
how can I do it then?
by having a system that manages every pawn's velocity based on your bullettime feature being active
with timescale staying at 1
isn't it easier to change 1 player instead of everything else?
I still want everything to be slowed down just his movement speed to be normal
and probably a few other things
I mean it's just his speed
bullets he shoots and all that stuff should still be slowed down
i guess as long as timescale wont go too low it should work
yeah but I still don't know what's wrong with my doJump function
everything else seems to work fine
what does "i fly up in the air" mean... isnt that what you want?
no
my guess is, you would have to update the whole physics simulation for your character to compensate for the timeScale
I want just a normal jump
well that's all the physics I have for him
left-right movement and jump
you arent doing any physics, the engine does that
yeah but my left - right movement works fine isn't it the same for up-down movement?
I can send you my whole code if you'd like to see it
no, because the jump relies on gravity that is applied by the simulation and not your overrides
so I should change the gravity somehow?
just add a scaled version of the gravity to your character with ForceMode.Acceleration in every FixedUpdate while bullettime is active
but it isn't always in the slow motion should I do it in the slow motion script then?
I don't even use forcemode.acceleration I used velocitychange
then start using it for the gravity
so I should change velocity.change to acceleration?
guess this is way too advanced for me, I'll come back to it when I finish other parts of the game
(make sure you consider the gravity that is already applied by the physics sim automatically)
its really basic physics... maybe you have to think a little bit about what you are actually doing to the physics when changing timescale
imagine your game remains in normal timescale... what you are doing now is just add a bigger jump because the gravity remains the same... what you actually want is a faster jump with the same arc, and that happens when you increase the jump's launch velocity and the gravity that brings it back down... the arc will be the same as for all other objects, but it will be faster proportional to timescale. Then if you play that world in the lowered timescale, your character will seem like it is at normal speed.
yeah I get what you are saying but the problem is I just started with unity and still have to learn how all that works I just recently made player movement controls and stuff this is way too advanced for me rn
is there a way to use the graphics buffer dynamically without setting a specific size for it?
im using this for voxels btw
I have an array of animations I want to attach to transform.rotation within certain range of eulerAngles. How do i do it?
I want to do it for 2.5d sprite animation rotation
I'm building a map at runtime. it's a 2d map using 3d tiles -- basically 3 states for each tile: pit, floor, wall -- what's the best way to actually render this all out at runtime? it seems like creating an individual GameObject per tile would have terrible perf quickly...
currently the map is 64x64 (meters) -- would be nice to have option to go up to 124x124
if the tiles have no Update methods its probably fine, definitely for 64 x 64
best is to test how far you can take it
alright, well if there's no reasonably easy alternative to just spitting out GameObjects that's what I'll do till I start hitting issues
i'd go with a more complicated approach only if it doesn't work performance wise
yeah, don't want to pre-optimize but also if there's something straightforward I can do which is known to work might as well start down that path
but all I can think of is trying to generate meshes at runtime, which doesn't seem simple
its not premature really, its a fundamental decision you cant easily change later
thats the way to do it, the other one (or an optimization) is compute shaders + jobs... but thats even more technical... but really all options boil down to combining meshes such that you have fewer game objects in a smart way
lol that'd definitely be beyond me at this stage
if you want crazy numbers of (active) tiles on screen, you'd probably have to dive into DOTS
I think in practice there won't be too many currently running an ortho camera w/ size = 4, so it's pretty tight and may zoom in more we'll see
guess I'll start w/ the stupid way, 64^2 tiles/gameobjects and see about fusing 'em together at runtime later
take a look at Broforce if you want a reference for what level of detail is easily possible with 1 gameobject per tile
https://docs.unity3d.com/ScriptReference/Texture2D.Apply.html have u tried using textures?
tell me more @hot tendon -- I'm not sure I follow? I want it to be 3d:
oh sorry may try converting it all into one mesh kinda how voxel chunks are created
https://docs.unity3d.com/ScriptReference/Mesh-vertices.html
@rugged pollen
gotcha, yeah you mean create a bunch of meshes based on the tilemap? yes I think that would probably be best but also sounds like a fair amount of work ๐
its not too hard but it will give you a huge performance increase because the whole map will be one mesh and with a benefits of being able to use a mesh collider
Hi all. I am having an odd issue. When I try to Attach my debugger to Unity (Visual Studio) I get an error saying there were build errors. But, there are no errors listed in the Error list window and if I don't debug, the app runs fine. I get the same error if I right click on the project and select to Build.
also with all the downsides that has
Anyone know how to fix that or what to look into?
whats the downsides of turning the map into one mesh?
Anyone know how to setup an HTTP Proxy with Unity Editor? I'm trying to debug something with mitmproxy, it is set as the proxy on the OS level, it intercepts every HTTP call on my machine right now, yet Unity somehow dodges it.
(net cut out) -- yeah wouldn't one giant level mesh collider be worse for perf? I guess I assumed it would
thinking, maybe another way about this is to try to use Unity's terrain system? feed the map data as height (which is basically what it is anyway)
terrain cant have vertical walls
I wouldn't mind if they're just really steep, I think
depends how big the collider but you be surprised the performance of phyx however you could split the map into chunks but I would go experiment
cant have sharp corners either
basically trying to create something like a little DoTA map or similar
here is a good way how to create the map however you will need to find out a way to color each vert
https://docs.unity3d.com/ScriptReference/Mesh.SetColors.html this is a way you could do it however if you want textures you will have to use uvs
@rugged pollen
I'll take a look, I think that makes sense ๐
currently going down the rabbit hole of trying to generate a terrain dynamically...
๐
crazy question but I'm thinking of making a doom "port" in unity
what I want is to have doom, in unity
it's probably a stretch and maybe emulation is what I need? but I have no idea
if anything, i have no idea how to run an emulator IN unity
I'll probably be better off making an emulator instead of making the game using the source code and assets
so I'm wondering if there is any emulator that can run in unity?
and if so, what can it run, how does it do it, so I can get an idea of what to do
why don't you just build it from the ground up?
like what's the point of emulating it in unity if there are already emulators out there
well I'm making a mod
that runs doom
that's really it lol
Search for "doom emulator C#".
looked it up and found a doom port for c# called managed doom, I've been looking around the code and found the renderer code, gonna dig deep tomorrow
thanks for the help!
it's good and ugly but here's where terrain + micro splat asset got me:
might work...
(from the main camera)
would be nice to smooth out those rough edges ๐ค
your concept image was much prettier
the one w/ the yellow square?
yes
there's definitely something appealing about minimalism like that. I agree that the above is pretty ๐คฎ
i'd say if you want a non-smooth look and steep walls commonly > 45ยฐ, terrain is not the way to go
i'd go for individual tiles and "bake" them into a single mesh-terrain when the level design is complete
How would I assign a scriptable object in my settings to be used globally by static functions for example?
as example the graphics settings in unity ^ where they also use a scriptable object and assign it
Or is the best way to go about this just loading one from the Resources folder?
@snow grottoYou can assign scriptable objects at runtime, if you place them in the Resources folder
@snow grotto For example, if you have a SO of type BoolValue in your Resources folder (you can have subfolders like I have here), you can assign the SO at start like this: ```
[HideInInspector]
public BoolValue MyScriptableObject;
protected void Start()
{
MyScriptableObject= Resources.Load<BoolValue>("ScriptableObjects/NameOfSO");
}
I'm doing that at the moment, I guess it woks fine. It would be nice to be able to assign it in the project settings somewhere though
Oh, maybe you can do it by writing an extension or something?
Ye I might do that, but I'm not sure if that's worth the effort ๐
I'll probably do that when the project progresses
I have a script that should sit in th eeditor and scripts folders each, same script. I am wondering if I can add compiler directives to enable this? I need to control the class derivation too: EditorWindow and MonoBehavior.
And does any body have any info on using #include to use files. This seems to me to be outside of the way Unity folder structure is setup. How does Unity handle *.h files?
This way I could have an H file that houses the variables and pull that into either EditorWindow or MonoBehior scripts.
The main goal is to one script that can be placed into the scripts and Editor folders.
you have to let go of your C/C++ concepts, header files don't exist in C#, a script in the scripts folder will also be automatically visible to any script in an editor folder (or rather the assembly that is compiled for editor use from those files in the editor folders). You can put a preprocessor command #if UNITY_EDITOR ... #endif around any code in any folder that you want to compile only inside the editor.
Correct. But I have methods and declarations that need to exist in both the Editor and script folders. I am trying to maintain only one script per folder while both scripts can see the each other. The 'seeing each other' I have accomplished. Now I want to maintain one set of methods. The easiest way would be to use directives but I can not find the directive that works for the two folders.
I've had some success with having another project generate a DLL and deploy it to my unity projects
It's not the .. best approach for everyone, but it works for me for my use case since my unity clients are a small subset of my total project
Yes. I would like to create one script and drop it into both folders but the compile and location has problems.
I don't have Unity open atm, but you really can't just using in your Editor script to reference the methods you need access to?
Yes. I am close in this. But the duplication of variables is what I am trying to avoid.
Maybe I'm not understanding.. do you have a singleton that you want to find and reference from your editor script?
Like, what are you trying to do? And.. are you super experienced in c#? or is this more of a beginner question?
40 years in C. No singletons. I have methods and data declarations that exit in two scripts at the moment. They are the same but the Editor has onGUI and editorGuiLayout. I want to maintain one script and drop that into both folders so I can use from the Unity menu bar and also attach to GameObjects. The script grew from a gameobject script to a editor script. My devlopemtn then grew the editor script and I now need that back on a gameobject too.
The script has to be derived from EditorWindow and MonoBehavior to reside in the respective folders and work correctly in Unity.
This is only to reduce the 'double editing' on two files.
Just extract the shared code into a class that is used by both "scripts", the editor one and the monobehaviour one, this is really basic OOP.
40 years, sheesh
Then each top level script will make calls. I get the class data as references for the Gui part.
make any ground breaking projects?
Yes. All the telescopes around the world sold by Software Bisque transmit the increments from the scopes to their PC code. This even includes Mnt Wilson at the initial debue. Now the militaries around the world use this same for tracking satellites and black orbital devices. One line of code, one week, $250.00. I basically wrote a mouse driver.
A multipoint measuring device for reading the fit of amputee sockets. I designed the leg hardware and the Pc side and comm. I hold a patent for it.
Not bragging. Just keep on walking the coding adventure and good things find you.
have you made a Pong clone?
my raycast is based on edgecollider2d.bounds.extents.x
any reason why it is "expanding" during rotation?
Bounds are axis-aligned
in this case, what would be the best way for me to get the fixed " width" ?
currently , im giving a fixed float value for the raycast position
Could just use the size field on the box collider and some local direction usage to get your extent point.
Vector2 size = collider.size;
Vector2 positiveExtent = transform.position + transform.right * (size.x * 0.5f);
that is kinda what im using to rectify the problem temporarily
One better: I wrote a Doom like game in Dbase before Doom. I was aiming for multiplayer before it was possible with other tools. I exported all records to a text file. I then used Basic to create an Autocad input file so I could view the 3d maze that the player's moves generated.
I need some help. "How do I install an asset store asset from within a github action?" is the overall question I'm seeking to answer in my programming session right now.
Context:
- I use game.ci and github actions to build my unity projects (usually webGL).
- I now want to use asset store assets for GGJ. My issue is that I don't want to version control unity asset store assets in my github repo.
- The asset store asset I want to install is (https://assetstore.unity.com/packages/3d/props/polygon-starter-pack-low-poly-3d-art-by-synty-156819)
I'm kind of having trouble. If anyone can help, that would be awesome!
Code of what I've tried so far (failed; unknown package identifier because com.synty.PolygonStarter was a guess)
using UnityEditor;
using UnityEditor.PackageManager.Requests;
using UnityEditor.PackageManager;
using UnityEngine;
public static class UnityBuilder
{
private static AddRequest _request;
[MenuItem("UnityBuilder/Install Asset Store Assets")]
public static void InstallAssetStoreAssets()
{
Debug.Log("Installing!");
_request = Client.Add("com.synty.PolygonStarter");
EditorApplication.update += Progress;
}
private static void Progress()
{
if (_request.IsCompleted)
{
if (_request.Status == StatusCode.Success)
Debug.Log("Installed: " + _request.Result.packageId);
else if (_request.Status >= StatusCode.Failure)
Debug.Log(_request.Error.message);
EditorApplication.update -= Progress;
}
}
}
My .gitignore looks like...
/[Aa]ssets/PolygonStarter.meta
/[Aa]ssets/PolygonStarter
The observable side effect that I'm looking for right now is being able to install this package from just my C# script from the MenuItem attribute. If I can do that, I'm basically done.
Like, is UnityEditor.PackageManager even the right API to install something from the asset store?
No. The package manager window lists the asset store assets you have and just downloads the .unitypackage and puts in folder somewhere and then imports it.
The best way I can imagine you doing this is, open up a new unity project, import the asset, git init that package, make a package by putting a package manifest file, and push it to a private repo you have.
Then you install it via the git url.
the disadvantage of this is... the package installed through the package manager (the ones with the package manifest file) is now immutable.
The best way I can imagine you doing this is, open up a new unity project, import the asset, git init that package, make a package by putting a package manifest file, and push it to a private repo you have.
Then you install it via the git url.
Hmm. Cool, I think I know how I could achieve this. Still, I wonder if there is a better way?
Is there a scripting API for the asset store? I couldn't find some documentation for a C# scripting API for asset store assets ๐ฆ
@violet schooner https://docs.unity3d.com/ScriptReference/AssetDatabase.ImportPackage.html I wonder if this will work.
Edit: supporting doc: https://docs.unity3d.com/Manual/upm-assets.html
I mean it should work. but you also have to download the .unitypackage file first and then import it.
Yea, I saw that and started discounting it as a solution ๐ฆ
I'm now trying to find the unity rest API. Look at this code: https://github.com/mukaschultze/unity-asset-store-api/blob/master/src/index.ts
I wonder where https://publisher.assetstore.unity3d.com is documented at. Presumably there is an official restful API document?
No luck. Well, at least there is more code that references that base url: https://github.com/search?q=https%3A%2F%2Fpublisher.assetstore.unity3d.com&type=code
I know no better than you. ๐
@violet schooner No worries, ha. Want to join me on this journey? I just stumbled on https://publisher.unity.com/access
(edit) dead end >.< There is an API to managed your own asset store assets but not others (like from Synty Studios)
I'm kinda grasping at straws, though. I'm hoping I can figure out how to programatically download and install asset store assets from a C# script <.<
If anyone has already done this, help would be much appreciated!
Is this the 'correct' way to handle server & client separation?
I know there's many different ways, but. I'm just having it disable either the Server or Client component under the shared (top) one depending on which version is running. But it means any script with both a server and client aspect will require three scripts total, so it bloats the hell out of the inspector.
Just doing if (isServer) or etc. seems very inefficient though so I'm not sure. Is there a better way?
I'm not even sure if that's possible. Afterall asset store packages are linked to your account specifically and if you supposedly could get them to download via script, you'd have to also pass your credentials which is terrible to have on github
I figured whenever I went through the activation flow (https://game.ci/docs/github/builder#buildmethod ) then the CI system would know who I am, and therefore know what assets I have (free or paid). No needing to share GitHub credentials at all.
The issue is figuring out how to programmatically download the assets. If I could do that, I'm good.
private void CreatePyramid()
{
Vector3[] vertices = {
new Vector3 (0, 0, 0),
new Vector3 (-1, 1, -1),
new Vector3 (-1, 1, 1),
new Vector3 (1, 1, 1),
new Vector3 (1, 1, -1)
};
int[] triangles = {
0, 1, 2,
0, 2, 3,
0, 3, 4,
0, 1, 4,
1, 2, 4,
4, 2, 3
};
Mesh mesh = GetComponent<MeshFilter>().mesh;
mesh.Clear();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
mesh.Optimize();
}
Can someone tell what wrong with this code? The Pyramid is not visible from all angles.
I think right now I'm just going to (1) make a private repo and version control the assets (boo!! I want to have my code publicly available!) or (2) just version control the free assets. It sucks but... well, that's what I have to do.
probably some triangles are facing the wrong direction, flip them by changing the vertex order in the triangle array
I tried that with no luck
The winding order seems correct
put the camera inside the pyramid, can you see the missing triangles then?
Uhh maybe not
if you cant see them from either side they don't exist or have zero area, or you have alpha clipping at 1 or you a transparent material that hides them or messes up the sort order.
no tutorials for weird number rules, but if you can explain the rules, you can also write the code to handle or render them, maybe based on BigInteger
var rot = Quaternion.AngleAxis(xAngle, Vector3.right);
var kaka = new Vector3(-1, 1, 0);
kaka.Normalize();
var lDirection = rot * kaka;
I am using the fallowing code to project and rotate vector along X axis, but its not working as expected
Its giving pozitive z values and ignoring x axis
Okay need some help with this.
I use a custom render pipeline to support a specific Oculus tech (SpaceWarp) and my current shaders don't support it.
If I build for android I want to change the shaders of all materials in my game to the simple lit shader. At runtime I just do .shader = simpleLitShader, but that gives graphical glitches because of spacewarp.
Now I am trying to do it in the build process, using the code below, but the materials stick with the old custom shader and not simple lit.
I also tried .material instead of sharedMaterial
Does anyone know if me or my code does something wrong?
public class ShaderSwitch : IProcessSceneWithReport
{
public int callbackOrder => 0;
public void OnProcessScene(Scene scene, BuildReport report)
{
foreach(GameObject go in scene.GetRootGameObjects())
{
var renderer = go.GetComponent<Renderer>();
if (renderer)
{
var tex = renderer.sharedMaterial.GetTexture("_Diffuse");
if (tex)
{
Debug.Log("did it for " + renderer.material.shader.name);
renderer.sharedMaterial.shader = Shader.Find("Universal Render Pipeline/Lit");
renderer.sharedMaterial.mainTexture = tex;
}
}
}
}
}
So is it not possible to install free assets from the asset store via a C# script? I'm not able to find a scriptable API for the asset store.
I can host my repo privately so I can version control the free assets for my CI builder but... I want my work to be public ( #opensource ).
Not sure about asset store but package manager has an API, maybe it works with the store too? https://docs.unity3d.com/ScriptReference/PackageManager.Client.html
I thought this myself but unfortunately it doesn't seem to work ๐ฆ
hey. any idea why an static List is being editted outside my codebase ?
I have this list called liveInstances. it's only call is on Awake from multiple objects
debugging it. the first call makes the Count 1
and then on the second object, it's Count is 0 again
adds to it and it's ` again
and 0 again for the next object :/
sorry for the mess.
It's a generic type. Are those all from the same closed generic? Otherwise, maybe you have let the list escape by returning it somewhere and something is modifying it
the thing is that nothing is modifying it at all. I checked with VS (first picture)
can you show the complete class code where you're getting list count as 0 even despite adding them before
all classes where you're adding items to list*
using System.Collections.Generic;
using UnityEngine;
namespace UpgradeSystem
{
public abstract class UpgradeItemButton<T> : MonoBehaviour, CanvasSystem.IOnCanvasEnabled
where T : UpgradeItem
{
public T upgradeItem;
public AudioClip popInSound;
static List<object> instances = new List<object>();
private void Awake()
{
instances.Add(this);
Debug.Log($"Added {name} to instances. count : {instances.Count}");
}
private void OnDestroy()
{
instances.Remove(this);
}
public virtual void OnCanvasEnable() => UpdateVisuals();
protected virtual void OnEnable()
{
//AudioSource.PlayClipAtPoint(popInSound, Vector3.zero);
References.staticSounds.Play(popInSound);
}
public abstract void UpdateVisuals();
public void Upgrade()
{
OnUpgrade();
//update visuals for all live instances / buttons
foreach (var instance in instances)
{
((UpgradeItemButton<T>)instance).UpdateVisuals();
Debug.Log($"updated {instance.ToString()}");
}
}
protected abstract void OnUpgrade();
}
}
ignore the rest of the code.
there is one possible explanation for this. despite a field being static, it is not shared among different generic types.
I thought about that too. maybe some old csharp thing that only the csharp devs at microsoft know about
I changed teh list type to object
the only way to avoid something like this is to put your list in some other non generic class
with the list as object, it's the same
yes. that would work I think.
but I believe C# has a feature for this situations. it seems very unproductive to have to make a helper class just for the generic static variables
@tough tulipyes your suggestion worked. thanks
(but at the cost of a new static class as a helper)
generics behave differently with static classes because generic class type 1 and generic class type 2 have completely different memory footprint depending on their Types. so they're entirely different classes
isn't there a solid singleton way of adding static variables for the parent though?
no
it's a shame really
@tough tulipseems like there is a solution for that
a nongeneric abstract as the parent of the generic abstract
isnt that same as having a helper class? either way you''re needing a new class
public abstract class GenericClass
{
static public List<GenericClass> instances = new List<GenericClass>();
}
public abstract class GenericClass<T> : GenericClass where T : SomeOtherClass
{
...
}
yeah , but neater
just out of curiosity what does abstract + virtual void mean
abstract forces a derived class to implement a method with that signature, virtual allows the derived class to override the implementation of the method that is defined in the abstract class. void means the method returns nothing.
I am creating a texture from code. These are my UVS, one simple triangle on the texture.
float triHeight = Mathf.Sqrt(3) * 0.5f;
Vector2[] uvs = new Vector2[] { new Vector2(0.5f, 0), new Vector2(0, triHeight), new Vector2(1, triHeight) };
Now I am to create the texture, and for each pixel I want barycentric coordinates matching the uv specified above. How would I best do this?
Obviously trying to avoid a full ray/triangle intersection since I have so many constraints that should be able to speed the math up
actually i think i got it..
yup, pretty close
I'm late, but you should normally be able to loop through the array to sum all the vectors, then divide by the length of the array to get a mid point.
That's how we do it in 3D, not sure if it's the same for UVs and whatnot
Anyone know why my HDRP Custom Pass which renders another camera onto a render texture is not rendering the sky color and seems to cut off object based on my rotation? I'm still learning Custom Passes and followed this example: https://github.com/alelievr/HDRP-Custom-Passes/blob/2020.2/Assets/Scenes/CameraDepthBaking/CameraDepthBake.cs
I created seamless portals, however using multiple HDRP cameras was too costly. I'm hoping by using Custom Passes I can avoid this performance drop.
thanks :D
Hey quick question, what is the difference between ComputeBuffer.Dispose and ComputeBuffer.Release?
Release() is implemented as ```cs
public void Release() => this.Dispose();
Dispose zeroes the pointer to the buffer and notifies the engine it is no longer needed
Release probably exists for compatibility or legacy reasons, Dispose is part of the IDisposable interface and allows you to define a scoped variable that is automatically disposed when the control leaves the scope ```cs
using (ComputeBuffer x = new ComputeBuffer(,))
{
// use x here
}
//this to pay for the Item over the network
[PunRPC]
void RPC_PayForItem() {
SaveLoad.gameData.playerMoney -= priceOfItem;
}
``` Hey guys so I am using photon pun 2 for networking, I have been trying so hard to figure out how to sync an int over the network so that both players see and get the same number. I want both players to have the same money basically. So when I connect to the network, everything works except this. I have watch like 10 youtube videos, read all the docs, I dont know why but I just cant understand it. As far as I know I need to use PunRPC, but running this just yields the same result for me. What key part am I missing? thanks
You need to actually call the RPC through the Photon API.
Simply calling it won't invoke it (I'm pretty sure)
I haven't used PUN 2
Photon Unity Networking framework for realtime multiplayer games and applications with no punchthrough issues. Export to all Unity supported platforms, no matter what Unity license you have!
PhotonView photonView = PhotonView.Get(this);
photonView.RPC("ChatMessage", RpcTarget.All, "jup", "and jup.");
So you'll need to do something like:
PhotonView photonView = PhotonView.Get(this);
photonView.RPC(nameof(RPC_PayForItem), RpcTarget.All);
That will also invoke it locally so you don't need to call RPC_PayForItem directly
Do I call this in start? I read this before but it confused me so much
You call it when you want it to be called.
because the example was with strings
When you want priceOfItem to be subtracted from playerMoney
So I call it inside the [PunRPC] ?
hold on
if (Physics.Raycast(ray, out hitInfo, Mathf.Infinity, Terrain)) {
if (Input.GetKeyDown(KeyCode.Mouse0)) {
if (hasSpawnedPrefab == true) {
RPC_PayForItem();
hasSpawnedPrefab = false;
Debug.Log("Placed Object");
}
}
}```
Do you mean call it here?
don't do this:
RPC_PayForItem();
That's a direct invocation
Instead do this: photonView.RPC(nameof(RPC_PayForItem), RpcTarget.All);
Assuming you want to send it to all
Although the whole thing looks a bit odd...
Does each player have their own playerMoney?
If so I'd recommend putting that in your player properties
And not using an RPC at all
Ill try it out, ive been stuck for so long. At the moment yeah, thats why I want to sync it
ohh
Well if SaveLoadData is only for each player, then doesn't that mean that calling this RPC will decrement the cost from all players?
Do other players need to know how much money you have?
Yeah i basically want to decrease it for all players
Oh right. In that case what you have is probably fine.
all player should have the same money
Right. In that case you could put it in the room properties?
But this will be fine too.
room properties?
It's part of photon
If every player in the server shares the same pool of money you could set that as an integer in the room properties
sorry im new to photon ive been ripping my hair out lol
My current int is actually set in a Json save file
Anyway, when a player buys something, you can send that you want to purchase something to the master client, then they subtract that amount from the "money" room property.
which is saved on every players pc
yeah let me test what you said real quick
got an error
RPC method 'RPC_PayForItem()' not found on object with PhotonView 2001. Implement as non-static. Apply [PunRPC]. Components on children are not found. Return type must be void or IEnumerator (if you enable RunRpcCoroutines). RPCs are a one-way message.```
maybe because im using photonview? this script is currently on the mainCamera
[PunRPC]
void RPC_RequestPurchase(int cost) {
if (!PhotonNetwork.isMaster) {
Debug.LogError("Should not be called on non-master client");
return;
}
var prevMoney = PhotonNetwork.room.CustomProperties["money"];
var nextMoney = prevMoney -= cost;
if (nextMoney < 0) {
Debug.LogError("Cannot afford");
return;
}
var changed = new HashTable();
changes["money"] = nextMoney;
var expected = new HashTable();
expected["money"] = prevMoney;
PhotonNetwork.room.SetCustomProperties(changes, expected);
}
void BuyItem(Item item) {
// do stuff...
PhotonView photonView = PhotonView.Get(this);
photonView.RPC(nameof(RPC_RequestPurchase), RpcTarget.MasterClient, item.Cost);
}
something like this
Did you call it on the right object?
I've never used photonview
Trying to process all of this hold on. And yeah as far as I know, its all done in the same script
This is how you'd do it using room properties
Which is appropriate for your situation
Basically anything that is an attribute of a player should go on player properties, anything that's shared between all players should go on the room
how is the cost variable at the top set? because I dont see any changes
When a player connects to the room they get all the current room properties, and whenever they're changed they all receive them
You call arguments to PhotonView.RPC
So the flow is this:
player requests purchase of cost from master client -> master client checks that money is available and updates shared money -> updated shared money amount is propagated back to clients.
You'll need to listen to OnRoomPropertiesUpdated in each client to see when the total money changes https://doc-api.photonengine.com/en/pun/v2/class_photon_1_1_pun_1_1_mono_behaviour_pun_callbacks.html#acd0123ad271eaa8bc372debcd33d0e31
void OnRoomPropertiesUpdated(Hashtable propertiesThatChanged) {
if (propertiesThatChanged.ContainsKey("money")) {
Debug.Log("We now have $" + propertiesThatChanged["money"]);
}
}
Something like that
Yeah im just trying to process it all
It's a bit of a fuckaround, but you can generalise this stuff
my brain is exploding right now
Multiplayer is hard
Yeah ive tried it many times before and failed
but ive actually got it working this time, except this one part to sync variables
Yeah so room properties auto-sync between clients. They just have their own way of working
So room.SetCustomProperties to set -> OnRoomPropertiesUpdated to listen for changes
And the master client should be responsible for changing them
So you need to notify the master client that it needs to be done
But they will be synced
Yeah i think I get it in theory a little bit anyway
You can also sync stuff like current game state through these
For example whether the game has started
Each player adds "ready: true" to their player properties
And when the master client sees that everyone has done this it sets "isGameRunning: true" in the room properties
When clients see that they all load teh game scene
They can also set the level there so they know which scene to load
It's pretty robust in my experience
Yeah, If I can get it working, ill probably end up using it for so many things
Yeah, you can write helpers for it
Doesn't need to be this verbose
Anyway, good luck. Hope it helped point you in the right direction.
Kinda busy with some work but if you get absolutely stuck you can DM me
Might be slow to respond
@kindred tusk Dude, thank you. Because of you I got it working
the room settings I havent messed arround with but after some testing with this CS PhotonView photonView = PhotonView.Get(this); photonView.RPC(nameof(RPC_TesMod), RpcTarget.All); I managed to fix the error. It was because the game object that the script was attached too, needed the photonView Component
But the room settings stuff Ive kept commented out and im going to mess with it a bit later. Just thank you again so much, been going crazy for days
Am I not able to use world space normal maps with the standard shader? I am finding surprisingly little information on this
Or well, it'd be in object space. But still
Hi. I want to draw a solid arc at runtime. Like this one https://docs.unity3d.com/StaticFiles/ScriptRefImages/DrawSolidArc.png . What first comes to my mind first is a triangle fan. Or can you suggest better way to do this?
Either a triangle fan or a single quad with a texture or custom shader
Custom shader will give you the best accuracy but if you need other shader features it might not be the best fit for you
A shader could be faster. I would just discard the color out of radius in pixel shader. But i need to be able to define start and end angle, so it gets trickey there.
Yes any angle
Discard pixels might give you hard ugly edges that are difficult to aa iirc
Ok so in your fragment shader you'll get the vector from the current pixel to the center in uv space, the current pixel will be between (0 0) and (1 1)
The center is (.5 .5)
Use magnitude to check the length, discard magnitudes over 0.5
Use atan2 to get the angle and discard angles you dont want
If you dont want a sharp pixel edge you can simply modulate the alpha when near the limits
The built in quad in unity should already have the correct uvs so all you need is to change the shader to your own
Hmm will try this. Maybe can be done even in shader graph.
How does atan2 work?
@primal flame You could use these https://iquilezles.org/www/articles/distfunctions2d/distfunctions2d.htm (Pie - Exact is the right one) to get closest distance on that arc. Then you can use partial derivatives (fwidth(sdf) ig?) to get nice looking edges at any distance.
You input x and y and get an angle(in radians) back
Ouh
Ok tnx
Could be also an option. Derivatives are expensive tho?
It has center and radius as input
What defined the angle?
Depends. They are quite expensive but remember hearing they are much faster than sampling texture for example. Depends what you compare them with. Gpus are quite fast nowadays
Yep, no center
Tnx.guys.
Just tryna understand/resolve this issue: So in the above, I have coroutines that I want to complete [CloseSwitchBoard triggers other coroutines], but each has the coroutineRunning check. Is there a way to have the loop completed then everything else below,
or some way to get the coroutines run concurrently and keep the checks in?
Create an Action that executes the method calls after the bool is set to false
tryna wrack my brain how idk
alright, so- I need my camera to scale to the correct ratio for visibilitys sake [ie adding a black bar top/bottom/left/right or stretching depending on the situation]
so that everything will be scaled correctly regardless of the screens aspect ratio.
I have already found a script that does this beautifully.. for one camera.
problem is I don't have just one camera.. I have two. the 2nd one is for a minimap thing.
and I can't figure how I would keep the minimap in the same [relative] space at the same [relative] size to the other camera on screen.
ie; regardless of the window size, it would be made to fit like so:
Hello, I've made this diagram for my problem but I'm stuck because I don't know if I have to use a design pattern, or use abstract classes or use interfaces. I've read many many articles and documents, but I can't seem to find which way to do it the best. If someone can advise me to the good way I would appreciate it, thanks in advance
Given your diagram both interfaces and abstract classes can be used for BusinessFolder and BusinessWorkbook.
So it all comes down to what is inside of them. If you need an implementation (virtual methods, private fields with a constructor to init these fields), then use an abstract class. Otherwise use an interface.
Thank you for your answer sir, do you think it's worth it to use a factory design pattern considering I'll have more BusinessFolders and BusinessWorkbooks in the future ?
what should that accomplish
Factories can ease out the creation and initialization of objects, so why not. Could also use generics in the factory class, something like public static T Create<T>() where T : new(), BusinessFolder for example
So you can do FolderA a = FolderFactory.Create<FolderA>()
What I'm slightly concerned about is for these concrete implementations, if they aren't different in any way compared to the base class, then use instances. So the two "base classes" are not abstract anymore, and you create several instances of them
But again, it comes down to what data is in these classes, and this isn't specified in that diagram
I'm trying to automatize my task at work.
We open a folder named for this example FolderA.
FolderA must always contain WorkbookA and WorkbookB (WorkbookA is different than WorkbookB).
Then I have to open each workbook and control values inside it.
That's why I created a base Folder class, and I inherit my folders from it but each folder must have different workbooks inside it. I have to add a method to control the validity of the folder (if it really contains both workbooks) and if yes I have to make a method to control the validity of each workbook by telling for example that cell range "C3" must contains a number value
I don't know if it's more understandable ^^
By "we open a folder" you mean a logical folder on your hard drive? Or is it a type from another software?
I also fail to see how this is related to Unity for now...
yes a logical folder in my hard drive. Hm sorry it's not really related to unity but I thought I could ask C# questions there
Okay, so that logical folder contains "workbooks", what are those, files?
Ah alright. I start to see an architecture here, that could be converted to C# types
It would actually be just one type, not abstract nor static, BusinessFolder, that contains the path to the folder, the name of the folder (can be determined with a computed property and an IO call), and an instance of Workbook whatever SyncFusion calls it.
Then, you would have an interface, IFolderValidator that declares a void Validate(BusinessFolder folder, ReportContext ctx) (where ReportContext is a utility to report errors to the user via dependency-injection).
And multiple concrete implementations of IFolderValidator, depending on what to validate in those workbooks. Say the sheet count, then make a class SheetCountValidator : IFolderValidator and check for that in its implemented Validate method.
Pseudo-code of the validator runner:
List<BusinessFolder> folders = // ...
List<IFolderValidator> validators = // declare validators here
// somewhere else
foreach (BusinessFolder folder in folders) {
ReportContext ctx = new();
foreach (IFolderValidator validator in validators) {
validator.Validate(folder, ctx);
}
foreach (Error e in ctx.Errors)
// Print error or whatever
}
Wow I've understood, I didn't think to make the validity logic an interface, I was just creating methods and I felt overwhelmed by all the code, thank you again I'm going to try rn ๐
fizzbuzz enterprise
What means fizzbuzz ?
Is it possible to have a build out development build listen their PlayerConnection on a set port number? For remote profiling of a server
meme repository
For as long as i've known, it always picks a random port on startup from a range starting 54998. But I wonder if they has been "resolved" lately
What is going on in here haha, it's the perfect depiction of enterprise code
Had to step up the architecture game, in case their manager finds that code
Is it negative ? It means I'm doing something too complicated from a pro point of view ? I love coding I would like to be better so it affects me ๐ฆ
Nah it's not negative, it's just an architecture that allows you to add things very easily. And to ease out things you have to complicate the code a bit with design patterns everywhere. Implemented right, it's a proof that you can make complex applications
And to be honest, I wish all the code in my company had that kind of architecture, it's a mess currently
But as long as your code isn't like that ^, you're mostly fine
Oh thank you ^^ So I should avoid to do a fizz buzz pattern, I didn't know about that, I'm going to try to follow your advices for now, I'm glad to have talked with you ๐
fizzbuzz is the name of a kids game and a common code interview question, usually considered very basic and solved in a few lines of code.
I didn't know, thank you for the details
It's more of the "enterprise" pattern here haha, that has a tendency of overcomplicating the code to do a simple task
But since verifying Excel file contents automatically isn't quite a simple task, a more convoluted solution is needed
For comparison you can look at Gitea sources (compact Go core, github clone) and Gitlab (full rails fizzbuzz 20 frameworks upon frameworks)
I have a github with what I did already (before asking for help) I don't know if I provide it to you if you can tell me what I did wrong, I didn't have professors or friends to help me I'm basically the only guy programming I know so I can't know if what I do is shit or no
If it's a boring request tell me and I'll let you go about your business ^^
Yeah you can send the link, I can do a quick code review if you want. Without the context, so it'll be purely about code architecture and conventions
Thank you ! you're going to pull your hair haha ^^
For context it's a bot that goes to our website and do actions like downloading the zip file, extracting it, then control the folder, control the workbooks you'll see
(I sent you the link in PM)
Has anyone reverse engineered asset store API calls [0] in order to download asset store assets in a CI/CD system? I'm doing it now because 1 I want my code to be public (for public consumption and for github pages) 2 I use github actions as my CI/CD system (automated testing and building for unity projects FTW!!) and 3 I **legally **can't nor want to (portability reasons) version control assets from the asset store (even if they are free!). What a pickle ๐ฅ
Fortunately, if I can write an editor script in C# that can download and import packages for my project then I can add that to my build process [1]. Unfortunately, unity hasn't provided a scriptable API for the asset store and thus I must reverse engineer the RESTful interactions from unity's decompiled code (see [0]). There are a lot of collaborating classes to make the REST calls so it's a bit of slow going to piece it together.
So far I've figured out a call to get a valid login form
curl -vL https://assetstore.unity.com/auth/login
The next step is to write the C# script version of this curl command, log in, and store my session data. Then I can reverse engineer the REST calls to download and then import the downloaded .unitypackage files into my project.
Anyways I figured I would reach out here for some help. I am very interested in any sort of advice. I would be thrilled if this is an exercise someone else has already done the work on. At the very least, if I'm the first guy doing the work then I might as well build a CLI tool and a (series of) blog(s) to help others in a similar situation.
[0] https://github.com/Unity-Technologies/UnityCsReference/tree/master/Modules/PackageManagerUI/Editor/Services/AssetStore
[1] https://game.ci/docs/github/builder#buildmethod
P.S: how I've been avoiding this issue in the past is just authoring my own sound, music, and 3d model assets (which I then own the copyright for by default) and then version controlling those assets. For global game jam, I really really want to leverage free assets from the asset store >.<
Just in case it hasn't occurred to you, have you considered hijacking UPM instead? It might be less effort
Can you elaborate? If I can find a lower effort solution I would be thrilled ๐
well, you have the source to package manager. All of that is accessible to you with reflection. So if you can figure out what it does in the UI, you can just make it do whatever it does for downloads with your own script
I think that's what I'm doing with my [0] link? I may be misunderstanding something.
Ultimately, the asset store "package manager" UI calls those classes to ultimately make REST calls to unity's API.
...Right?
If the package manager API to download asset store packages isn't public and supported, you might be safer reverse engineering the REST API. Unity defined their REST contract and won't change it lightly because it might break multiple tools and processes. If you use the internal package manager API you could still be affected by REST API changes on top of changes to only the package manager API, so I don't think it will be worth it (unless things have changed in the last year and they have public C# calls available now).
hey all im trying to add arkit/ turn on arkit via the xr-plugin-manager api in my ci/cd but it doesn't seem to work although if you check the value it says its on. anyone have any ideas or what channels i should ask?
Anyone experienced with procedural normal maps?
cant find any proper documentation
I cant seem to use normals facing in all directions, and I assume that is related to tangents
its a simple triangle with uvs (0.5f, 0), (0, triHeight), (1, triHeight)
I have normals in object space I wanna put on the texture but not sure what kind of transformation i need to put them through
because of those UVS and my very limited understanding of tangents, i assume the tangent would be tris[2]-tris[1]
Color normalColor = new Color() {
r = objectSpaceNormal.x * 0.5f + 0.5f,
g = objectSpaceNormal.y * 0.5f + 0.5f,
b = objectSpaceNormal.z * 0.5f + 0.5f,
};
This is what I am doing and it clearly doesnt work correctly, the normals are mirrored across the z plane
I want to serialize a List of Transform values (position, rotation, scale). I want to be able to deserialize the data and reconstruct the values. Is there a go-to-solution or should I write my own Serializer. If the latter: Should I round the floating numbers to the 5th decimal digit since this will be "close enough" for reconstruction?
I tried a "i have no idea what i'm doing" approach: ```
Vector3 tangentSpaceNormal = new Vector3(
Vector3.Dot(objectSpaceNormal, tangent),
Vector3.Dot(objectSpaceNormal, bitangent),
Vector3.Dot(objectSpaceNormal, normal)
).normalized;
which provides light coming from roughly the correct direction, but its not quite accurate..
so close yet so far away.. i am so salty
// Texture settings
Texture2D normalTexture = new Texture2D(texSize, texSize, TextureFormat.RGBA32, false, true);
normalTexture.filterMode = FilterMode.Trilinear;
...
// Normal conversion
Vector3 tangentSpaceNormal = new Vector3(
Vector3.Dot(objectSpaceNormal, tangent),
Vector3.Dot(objectSpaceNormal, bitangent),
Vector3.Dot(objectSpaceNormal, normal)
).normalized;
Color normalColor = new Color(
tangentSpaceNormal.x * 0.5f + 0.5f,
tangentSpaceNormal.y * 0.5f + 0.5f,
1,
1
);
normalPix[i] = normalColor;
its very close to being correct now, its just that theres noticable edges between the different lit triangles (every triangle is its own mesh btw), shadows don't quiite line up and the shadow line isn't rounded. the normals are a perfect sphere so I dont expect the shadow lines to be perfectly straight in each triangle.
If i use an unlit shader and simply draw the object/world space normals to the texture, theres no seams. So its something wrong with either my tangents/conversion or the shader (standard shader).
And to reiterate, every triangle is its own mesh.
Could it be that unity is for some reason using vertex lights instead of pixel lights? 
Has anyone found a solution for rendering a dashed line in the UI?
@quartz stratus in the Editor or in Canvas?
In an Overlay Canvas for use at runtime
err, shitty link sorry, but premise is still true. you can use a Sliced sprite and use the Tiling feature
Oh snap this is promising. Thank you!
Protobufs are my go-to for serialization needs. Protobuf-net is a nice library for working with them https://github.com/protobuf-net/protobuf-net
thank you!
MessagePack is probably worth a look too, especially since it's made with Unity use in mind. https://github.com/neuecc/MessagePack-CSharp
Hey, does anyone know any custom matchmaking services I can use in conjunction with Netcode for GameObjects?
Hey guys can anyone know the reason that is it normal or not ? I created a command pattern based rewind system I am recording all that transform translate commands in update then rewinding but when i start with Vector3.zero position it not returns 0-0-0 but other values are working
Instead of coming to zero, it is stuck at a value such as epsilon, which is very close to zero.
How are you rewinding? If you're doing any addition/subtraction of vectors you will get small errors just based on floating point precision errors
yeah Translate does arithmetic
I'd say store a history of the actual positions and just restore that position directly, rather than translating in the opposite direction
but i will extend all of these action in future I want to rigidbody based physic rewind but in that scenerio just keeping pos,rot of rigidbody will work ?
e.g. instead of undoDir = -dir; just save undoPos = obj.position;
and to undo do obj.position = undoPos;
yes
it will work fine
You will also need to save the velocity and angularVelocity of the Rigidbody though
yeah tons of data ๐
also it will be more precise to save obj.localPosition and obj.localRotation
rather than position and rotation
I'll note this right away thanks a lot ๐
@sly grove I also forget the ask some physic question imagine we are goind A to B then a static object will appear between A-B and thats not rewindable when i rewind with phsyic rigidbody will not understand there is a new object in this situation what would u suggest ? creating a new physic scene and calculate every undo action with that scene returnable velocity ? or anything else ๐
When using FindObjectsOfType<> it gets every component of that type from the scene. Is there a way I can get the objects these components are attached to instead?
#๐ปโcode-beginner you can get to the GameObject that any component is attached to with the .gameObject property
thank you
Hi! I'm trying out A* PathFinding. I want to implement Breadth-first search to have my AI wander around my tilemap. I just copied the code from https://arongranberg.com/astar/documentation/dev_4_1_6_17dee0ac/wander.php but I don't know what to put in 'nodeDistance'. Anybody can help me with this?
Probably how far you want the target to be?
I tried setting to different values like 100,500, 2000 but my AI is only moving a tint bit from its location.
๐คท
Hello guys,
After many test with AsyncGPU, i have question.
Who is more efficient for no loose frame.
Step one with sync or
Step two with async ?
why not just use something like json?
Sync one would just execute the command right now and wait for it to complete, essentially freezing the main thread.
It needs to be uploaded to an SQL field - would prefer it to be one single piece of data. I thought about a base64 encoded byte array
you can just use the json itself as one piece of data
your value becomes something like
{
position: "10,5,6",
rotation: "10,20,0,0",
scale: "1,1,1"
}
it doesn't matter how exactly the values are serialized, as long as you are consistent between serializing and deserializing stuff then it should all be ok.
also more human readable in case you ever need to look at the values
@untold moth so async with request sometimes it's the best way to skip freezing ?
logic but real ?
Yes, if you want to do some task without waiting for it to complete immediately you use async operations. The downside is that you don't know when it's gonna be complete, so if you rely on the results, you either need to check it every now and then or subscribe to "on complete" callback.
yeah but it's better than wait 3 sec x) thanks because sometimes with unity's features i m not sure ahah
anybody else can help me?
im having some weird issue with Animator component. When i add a new gameobject to a gameobject which has animator, at runtime i'm unable to move the new gameobject
even though the animator doesn't modify the new gameobject at all
when i disable the animator, then im able to move the new gameobject
if i disable RigBuilder component, then also i'm able to move the new gameobject
nothing weird, it is being controlled by the animator/rig
want to move, parent to something
Reverse engineering unity REST calls is a chore. Haha, why can't installing assets from the asset store have a scriptable API?! Or why can't I version control FREE assets?! Unity! Get a clue! Software engineers want a CI/CD system testing, building, and deploying their stuff AND they want to use assets from the asset store >.<
(reeeeeeee)
why? the new gameobject is neither being moved by another animated in the animation clip, not does it is constrained in the rigging
wdym you cant version control assets?
i parented left hand target position to right hand. but im unable to move left hand target when i enter play mode
when i dont parent it under rigbuilder, it indeed works
Have you read the unity EULA for using the asset store? Version controlling assets is against the terms & conditions.
doubt there will ever be any issue with this
I figure most people using unity don't use public repos, but I want others to learn from my code. I have used github so many times and found other people's code. I want that experience for others
ah for foss
"Come on, rob the bank. It's unlikely the cops will catch you" lol
well asset store isnt github so yeah
It's still against the rules. Maybe Unity won't prosecute it now but eventually they will. Github has been executing DMCAs
use those that have gh sources
I found this tool openupm: https://openupm.com/ I haven't browsed extensively. You bring up a good point -- maybe I just use open source stuff.
opm is great
I can check for myself but... Does the package manager automatically install external packages and import the assets into the project? I'm not asking for my workstation, I'm asking for my CI/CD context (github actions)
- if they are imported from github source
Its okay... This sad community knows shockingly little about the advancements in other software spaces (automated tests, CI/CD)...
Honestly, I've thought about applying to work at unity to try to change things from the inside
It's just so sad to learn many friction spots exist for having your unity project be open to the public. I feel hobbled; I can't use the asset store for even free assets because I host my project publicly. Lame >.<
(edit) but then I remind myself of how much unity gives for free. I can't be too upset. I'm not. Unity is great.
you are aware that CI/CD, version control and everything you want to do is extremely expensive in the gaming space vs most other open source projects you come across. Unless you have a fully open source stack with all compatible licenses and projects taking just a few megs of space you are in the same boat no matter what community you are part of. This here is basically enterprise level complexity that even a hobby dev has to deal with when going slightly beyond basics.
your problem really boils down to money / licensing issues
No way it's more expensive than stuff in the enterprise software space. I mean, let me tell you (horror) stories about MsSQL, java, docker(!!), and microsoft licenses.
your problem really boils down to money / licensing issues
I disagree (politely). My problem boils down to the technology (unity) doesn't support what I'm trying to do. Primary question: why isn't there an asset store scriptable API like there is for everything else?
If you think assets in games are big, let me show you our 2GB java monolith that runs in a container ^^;;
I agree. Also, thank you for engaging me on this subject!
Unity's licensing is a part of why its not legal
How many assets on the asset store are under a permissive license? But the unity asset store EULA overrides any CC or MIT licensing
dont use assets then
or pay the dev to license something to you that you can use publically
what do you want really? people giving you stuff for free?
or pay the dev to license something to you that you can use publically
this is against the unity EULA. Unity can still go after me if I post assets they offer
what do you want really? people giving you stuff for free?
Well, kinda. I want the asset store to have a scriptable API so I can install free assets from the asset store in my CI/CD system
The fact that this isn't a legit operation is baffling. Why doesn't unity support this use case?
We have to ask for better as users of unity!
legal reasons
legal barriers that unity has put up...
to make money
yup
Hey guys, I'm at a bit of a loss here. If anyone could point me to the right direction I'd appreciate it!
I have a save/load system on my platformer game that uses a binary formatter. I want to be able to save a few things(puzzle state etc), including the player position, on a checkpoint at the end of each level. I currently do this by having a collider at the end of each level that:
1 - Saves the player checkpoint position to a list
2 - Adds a series of listeners(i think that's the correct term?) to events that are described in the inspector, most being related to saving the puzzle state
3 - Invokes an action on the main saving script that calls those listeners, adds their information to the list, then formats that list into binary and commits it to the hard drive.
4 - Invokes another action to remove the listeners
It works fine, but the game briefly freezes every time the script runs. This is obviously not okay, and kind of ruins the experience. I SUSPECT the issue is that I'm using [ActionName]?.Invoke() in the main saving script, instead of something asynchronous like BeginInvoke(). But I'm but a humble unity programmer and I know nothing about the more complicated C# stuff. I have no idea how to implement that, and if that's even the issue. As you can see on the screenshot, I do need the "continuity" that invoke provides so that I can commit the files after all actions are done, and then remove all listeners. I suppose the "callback" argument on BeginInvoke has something to do with this? Again I'm a total noob at these stuff XD
Any help is appreciated. Sorry if I interrupted any other conversation.
The authors of the work have put stuff up for free. I want to (1) have my sourcecode public so others can learn/be inspired by my code, like I have done so many times from other people and (2) install free assets from the asset store.
ok this is gonna be hard I guess
but I want to draw a mesh using just points
and then make a room out of it
so, I set some points on the floor
like, an outline
it creates a floor, and then the walls from those points
shouldn't be that bad ... https://docs.unity3d.com/ScriptReference/Mesh.html
user makes points (vector3 vertices); if a certain amount is reached (4 ... or more) you create the mesh with the coordinates
I need some assistance
I have an AI setup with navmeshagent component, I want it to TRY to set the destination and CATCH if it throws an error, which it should if the Agent component is disabled, but it throws an error anyway to the console saying it can only SetDestination on an active game Agent rather than displaying the set Log message.
Code Example:
try{NavMeshAgent.SetDestination(destination);}
catch {
Debug.log($"{game object.name}: Agent cannot set destination ");
}
What should show: 'GOName: Agent cannot set destination'
What does show: ERROR: "SetDestination" can only be called on an active agent that has been placed on a NavMesh.
Unity engine.AI.NavMeshAgent.SetDestination(Vector3)
It throws that error when trying to run the code with the Agent disabled, but it doesn't run the catch statement afterwards to display the desired message. Can anyone inform me why?
Has anyone here done 8DSR (Eight Dimension Sprite Rotation)? Please DM me. Its a question of code.
problem is it'll look something like this
like
you need to lock the coordinates of the points to one or two axis to keep it less ... wonky ๐ if I understand your sketch correctly
so let the player choose if vertical or horizontal ... one axis down. lock another axis depending on the location of the next point (above/below the last point; left/right) so you get a straight 90 degree angle everytime
zombie not so good in explaining ๐ฌ
Can someone explain the difference between Addressables vs Unity Web Requests?
UnityWebRequest is a web api that allows you to get things from the internet. adressables is an asset packing / distributing / loading solution
they have practically nothing in common
https://en.m.wikipedia.org/wiki/Polygon_triangulation
Its called triangulation, there's multiple methods here that should help you
In computational geometry, polygon triangulation is the decomposition of a polygonal area (simple polygon) P into a set of triangles, i.e., finding a set of triangles with pairwise non-intersecting interiors whose union is P.
Triangulations may be viewed as special cases of planar straight-line graphs. When there are no holes or added points, tr...
They put it up under unitys license, theres other sources that may fit your use case better. For example opengameart
A large percentage of the free assets on the asset store are samples, they are not intended to just be passed around for free, they are intended to get you interested in their assets and buy them. Without the context of the asset store, this doesn't work as well. Therefore theres very little incentive to allow you to pull the free assets in an automated fashion.
Someone that can help me with a getassetbundle from the web?
They put it up under unitys license, theres other sources that may fit your use case better. For example opengameart
But that's the thing... I don't want to have to version control 3rd party assets in order for my CI/CD system to build. It's... so clunky. Other languages utilize package managers (likenpmin the node ecosystem) so you don't have to version control 3rd party code. There has to be a better way
Therefore theres very little incentive to allow you to pull the free assets in an automated fashion.
I follow this logic. Where it breaks, though, is when I then talk about importing my paid assets from the asset store from a CI/CD context. There still isn't a scriptable API for the asset store where I can identify myself and download assets I've paid for.
There's the problem. It's like Unity hasn't considered the CI/CD use case. So how do people build their unity software using paid assets?
Well, most do it by going against the asset store EULA and version controlling assets from the asset store. This works if your repo is private, at least until GitHub allows DMCAs against private repos.
Obviously I get around this by just creating my own assets (which I then own the copyright to by default) and then I get to decide what can go where... But that is just not leveraging the asset store, lol.
Hi everyone, is it possible to have custom animation playables that have run on itโs own time when the timeline speed is 0? Iโm trying to sequence dialogues and animations together but during dialogues pauses the animations are pauses as well.
But they can be used together?
Of course
How does Unity make functions like Update() Awake() OnCollisionEnter() etc.. work? Is there a way were I can do this myself, to have classes inherit from a base class that allows all inherited classes to "use" the function instead of using overwrite
https://docs.microsoft.com/en-us/dotnet/api/system.type.getmethod?redirectedfrom=MSDN&view=net-6.0#overloads
if you know the method name given a type object, you can call it
Unity uses reflection. It's a lot more complicated and less performant than simply using normal inheritance patterns, and will make your code much more difficult to read and maintain
O okey good to know, then I'll implement my functions like normal Inheritance
addendum: they're called 'magic methods' and are generally something you want to avoid
Can anybody help me wit this?
if (B)
{
A = false;
playerCamera.GetComponent<Camera>().fieldOfView = Mathf.MoveTowards(playerCamera.GetComponent<Camera>().fieldOfView, 90, kickSpeed * Time.deltaTime);
}
if (A)
{
B = false;
playerCamera.GetComponent<Camera>().fieldOfView = Mathf.MoveTowards(playerCamera.GetComponent<Camera>().fieldOfView, kickPower, kickSpeed * Time.deltaTime);
}
if (playerCamera.GetComponent<Camera>().fieldOfView == 90)
{
A = true;
}
if (playerCamera.GetComponent<Camera>().fieldOfView == 95)
{
B = true;
}
Use a code block. See #854851968446365696, that's not easy to read and I wonder how the bot didn't delete that
In #๐ปโcode-beginner with appropriate code formatting, sure
Surely, somebody not new would know about these rules
Lies, deception
Is there any way
I can download a model from the internet with a web request
And put it in game as a mesh
During runtime
Okay, this's pissing me off. I'm trying to drop a monoscript onto a scriptable object to make an object.
I want to make an instance of a derived class and not the base class, but it's making me the base class. How can I make it more variable than it is now?
The SO.
https://gdl.space/aminofaqoh.cs
the base class
https://gdl.space/uvovuroqow.cs
And the subclass I want to create
https://gdl.space/ohuhayafic.cs
What I'm not getting from the inspector for the SO is the enum, just the float.
I suppose you'd have to first see if you can use a model outside of the project build during runtime. If so, the rest is just downloading a file and placing it in the right location on your device. for the first step, you'd have to check the restrictions on which directory can you pull models from on runtime. If the resource folder is accessible to download files to, you could start with that.
Yeah exactly, before jumping into the networking part, see if you can load a mesh that is stored on your filesystem first
Once you are able to, switching to the net download isn't hard, given that what's on your filesystem and what you're downloading has the same format
try making a custom editor
Maybe unity thinks what you are trying to do is a bad idea?
since the property you are serializing is a Effects and not the derived class, unity is creating the editor ui based on that base class
You have a public Effects rather than your subclass.
I believe that is intended, but the inspector wanted result is to have the other properties included from the sub class
Yes, because thatโs the base class. I want to make it variable so it can also be its subclasses as well.
Aight, I have no idea how I'll do that
But I'll take your advice for the model thing
Thanks!
In that case make a custom editor ui thingy
What Ark said.
The inspector can't show you information isn't privy to. So if you don't include the subclass, how can it know the enum?
And feared it would have to be that.
you can probably use reflection to just get your extra properties not to have to make one for each
It would be a drop down list.
Reflection?
A lot of information about your classes is stored and can be accessed using reflection on runtime
you simply take the System.Type of your subclass and get the properties and fields
go through those to take the public and/or serialized ones to then display them on your editor
that will return you FieldInfo or PropertyInfo types which contain all the information about the field/property
both of those have SetValue and GetValue methods you can use to get/set the values of the instance (which you must give in as a parameter)
you can easily loop those to then create a ui based on the type of each field/prop and call the get set values accordingly
If you get stuck, let me know and I can help you out with it
Could I see an example of it?
I can send you what I made to get all the fields and properties to dynamically create and handle sql tables
Essentially, you start by a method to get all those fields and props
The GetSetMember is a class I made to keep the props and fields in the same list since they don't both derive a class with the get set methods. you can replace it with FieldInfo or PropertyInfo depending on what you are using or make your own to do the same
private GetSetMember[] LoadSerializableFields(Type self)
{
const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance;
List<MemberInfo> members = new List<MemberInfo>(self.GetFields(bindingFlags));
members.AddRange(self.GetProperties(bindingFlags));
List<GetSetMember> serialized = new List<GetSetMember>();
for (int i = 0; i < members.Count; i++)
{
GetSetMember member = members[i];
if (member.Name == "Id" || member.IsNotSerializable) continue;
Type type = member.ValueType;
if (type.IsPrimitive || type == typeof(string) || type == typeof(DateTime)) serialized.Add(member);
}
return serialized.ToArray();
}```
in the loop, I don't keep the field with the Id name since in this example I am getting the fields for the sql table and already have it elsewhere so you can ignore that too
as your error says, at line 55 you are returning a different type than what your method return type is
read the errors please
understand the errors, study them
hello
I wish some help with a procedural animation code I'm doing
For some reason once the legs perform the first step, they keep moving nonstop
following the phantom target, What should only happen if the distance between the target and the phanton target exceeds the stepDistance
The weird thing is that I do this with a tutorial by a guy and he doesn't get this error
despite the identical script
That's what they always say
this is no advanced issue, begone! Return to #๐ปโcode-beginner ! (I'm joking, well kind of, learn your basics)
are you talking with me?
no, no
oh, okay
Considering how complex procedural animation is, I feel like that much code is very little to understand your issue. But I can say one thing with certainty: what is up with that... empty if statement?
Did you mean to use a continue; ?
well that Empyu if statment I was using for debug but I had deleted everything inside there and just left there in case I was use him for something beside the else statment
sorry if takes long for me to answer, my english is not one of the best
Okay somehow I just fixed by changing the order that these functions are being called, I just can't undestand why that fixed
I feel like you'd have to fill in what the code you showex is trying to do. I suggest you first comment out the code you don't want to run anymore so it does not interfere
And secondly, add some comments in your code saying what the lines do
well, it has comments, but they are in portuguese, so i deleted to post here
well, let's say it's been a adventure
i tried to follow 3 diferent tutorials, none of them worked
I have 7 attempts of making the same system
and this is the one I'm trying to create myself
using this video as reference https://www.youtube.com/watch?v=e6Gjhr1IP6w
I tried to explain procedural animation in 10 steps.
Check out my twitter: https://twitter.com/CodeerDev
yep, but I'm stubborn
yep
I'm looking for some help using DOTs and Burst compiler to run Jobs
NativeContainer wont allow me to use Structs as TValue's
Can't use Generics like List or Dictionary either ofc
I tried to be crafty and convert my structs into byte[] then convert the byte[] into int using BitConverter
But NativeContainer isn't serializable. is there anyway to have a dictionary or hashmap with a struct as a value?
Damn, sounds interesting but I don't know about these things. If you'd care to give me insight, I could brainstorm.
I barely do either lol this stuff is still all in beta/preview
Basically, the job system helps heavy calculations run faster: https://www.youtube.com/watch?v=3o12aic7kDY
๐ฅ Save 50% on ALL assets from Synty Studios with code SYNTY2021 (offer ends 9/11/21)
https://assetstore.unity.com/publisher-sale?aid=1100l3e8M
In this video, we'll use the Unity Job System to optimize some CPU-intensive code.
#Unity3D #GameDevelopment
Unity's Data-Oriented Technology Stack โ Unity DOTS for short โ is a package that consists o...
But, you can't use List, Dictionary any of that good stuff. You're limited to using Unity.Collections which are thread safe version of the generics
but they are super limited in return for being much faster and able to run on many threads/cpu cores
You also can't touch any MonoBehavior classes or static classes/variables
this guy just changed the int to var in his for loop, call the cops
okay, I watched your video but I am still not sure what you are tying to do
lol I mean I had no other choice
basically
I want to access a Dictionary<int, MyStruct> here within a job
but it won't allow for that, it only allows primitive or "blittable" types
Could you define a NativeHashMap<int, MyStruct> outside the job and use that everywhere instead?
Or does something depend specifically on Dictionary
(disposing of the NativeHashMap when it's time of course)
yeah, sounds like they have various alternative that you have to use
I can't really even define that, since it NativeHashMap won't allow the struct datatype. I also can't access any outside classes, because it wont allow me to reference classes within the struct x.x
yeah, really sucks tbh. would be nice to just be able to call stuff normally
To provide the best answer I can with the info here, it might be worth revisiting what you have laid out to see if it might be possible+worth refactoring some stuff in light of better knowledge of how you're going to need to interface it with jobs
e.g. if there are any classes that would be better off as structs, etc.
hey, for classes, ok so like... yknow how ridgidbody 2d options change if you choose a different option? how do i do that when i am making my own class?
ridgidbody dynamic
ridgidbody kinematic
see how theres less options?
some disappear?
how do i make my own classes have that? where some variables disappear if another is different?
you make a Custom Editor
what exactly does that mean/entail
it means you create a new class that handles drawing those thignies
so you can create extra boolean ui element that, when selected or not selected, change whether you draw x or y
yea thats what im trying to do
ok
cool
i will read this!
much appreciated!
odin I heard can help with that
Is mirror networking a good one to use for simple multiplayer games that will have p2p connection through steam? If not could you suggest some that are good and preferably free?
Mirror's good, they have a Steam Transport
native hashmap can contain structs
the defined syntax says so:
If it didn't allow structs it wouldn't allow anything. in fact it only allows structs
The only thing that might be non-blittable is this
I was under the false impression that Vector2, Vector2Int couldnt be used so I was using int2 instead
That might be the cause
um what about UnitPathfindingData?
Nullable types are definitely not blittable
Can you have nullable types? I've not thought about that before
Also, there's a bool and a class in there?
MultiCellUnitData looks like a class at a glance, but I'm not that familiar with VS' colour schemes
it would explain why it's underlining the nullable too
Let me remove the nullable types, then and try again
Unity.Mathematics has a bool1 you can use
well, it's either this or lag lol
what kind of game are you making?
yo guys, i have a b64 encoded gzip string im trying to decompress and have written a method to do so. this method works fine in the editor but when i attempt to build it just refuses to decompress the string
this is what im working with, the string itself is the variable data
Define refuses
the string that ends up getting built in null on device
but does get properly decompressed in the editor
and thats not from the try catch block, even without it this happens
Have yo uvalidated that your input data is correct at runtime?
Assuming you get it from disk or some networked api
its coming from my backend so invalid data would mean a user is up to no good
it which case, it would just fail the try catch block anyways
the issue may be coming from converting to bytes using base64
What build are you trying to make?
Mono or il2cpp?
If mono i dont see a reason why it shouldn't work in builds.
Why aren't you getting the exception object btw?
It would help you debugging process a bit easier
How do I go about 3d model animations, I have a person model that I want to set up to make it look like heโs walking when I walk
It somehow just occurred to me there's an #๐โanimation channel
Also try to avoid crossposting
also i'm not an expert, but i would be heavily against trying to jump nose first into 3d animation for an essentially beginner coder
It's obviously very possible cuz people do it all the time, you're just gonna end up failing 90% of the time, and the other 10% you create an abomination you can't do anything with
Any chance setting the Draw bool manually?
because I need to disable the Draw option in playmode but it seems to be locked
Anyone know what version of unity uses .net 4.6 or where I could find that information? I tried to Google it
But couldn't find it :/
It depends on your Unity version
Yes
yes when
haha that username
Are you sure? Man that doesn't makes sense
only a few months left
So if I use unity 2019+ , system.net.mail smtp should be using lts 1.2, right?
I don't know what "lts 1.2 means", but it should be available
I've also seen a warning on SmtpClient that it shouldn't be used anymore because it doesn't accept any new protocols. Using a NuGet package is recommended
Right so here's a context: I'm working on a legacy app cause for a few months the send mail feature stopped working on Android. Logcat tells me it's an smtp error, and sends me a link to an article saying that office 365 (the mail service we use) will no longer be supporting lts 1.0 and 1.1. So I'm thinking ok well I'll just look up what version of .net uses lts 1.2 but according to what you say we should already be using it.
Yeah I saw that too, I just thought I'd use the easy way out. I really don't want to change the 1.3k lines file that handle mails that was written a few years ago by someone who no longer works here.... Sigh, I'll guess I'll have to do it anyway.
@fresh salmon do you know if there's a way to check what version of .net I currently uses actually? Best I have is .net 4.x
Hm, can you try logging Environment.Version (using System;)?
If that doesn't yield results, try System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription
Thanks I'll try that!
Hey Guys, i have the following Problem.
I have Canvas for my Tutorial with an Arrow Element. I now just want to define on which element the arrow should point (The Element could be everything, Overlay Canvas UI Element, ScreenSpace Canvas UI Element, World Space element (3d Object and also worldspace ui). What is the best way to calculate the correct position for the arrow in all these cases. I also want to point the arrow for example on the top border of an element so it would be nice I somehow get the correct borders of the element the arrow should point to
Any Ideas?
So, just so I understand the problem, the arrow is in a locked direction, and you want to change its position so it always point ti whatever you want, right?
Lmao fitting username
Yes thats right
So a simple way to do it would be to have a canvas on your camera, and project the position you wanna point to on the canvas plane. That's where your arrow should point
If it's an ui element the projection doesn't change anything, and if it's a 3d object it'll project onto the correct position
I think there is a Vector3.projectonplane or something
Oh thats interesting
Yeah, all you need is the transform of the object you point to
The Plane would just be the ScreenSize, am i right ?
The plane in here is a theorical infinite plane that doesn't actually exists in your code
plane = new Vector3(Screen.width, Screen.height, 0f);
response = Vector3.ProjectOnPlane(targetTransform.position, plane);
Is this how the code would look like?
Or am i wrong in my thinking
?
No, you describe a plane using its normal. Here, the normal would be Camera.main.transform.forward
Interesting, i will try that, thanks
You should look up a bit of linear algebra, it really helps with these kinds of situations.
Okay thanks i will
Do you have any good talks or sources where i can look a bit deeper into this topic?
3Blue1Brown is a great youtuber when it comes to explaining Maths.
Just disable the terrain component and leave the terrain collider component active
terrainTexture = terrainObject.GetComponent<Terrain>();
terrainTexture.enabled = false;
Can any1 help with this? Basically trying to debug this, where I have an On/Off Switch using Coroutines to Open/Close a menu. If I spam Tab (The button to call it with new Input system), sometimes, the menu stuff stays, or the background doesnt fade to black.
Is there a way to fix this? as in let everything finish running before starting the other thing, even if im spamming the button
Trapeziums are Coroutines
and heres a print of the console
so I asked this yesterday
and I figured how to do what I wanted to
it was basically downloading a model from the web
I can import .obj files directly at runtime
and I wanna get models from the Ikea website
there's a download button
and idk how I would go about getting a list off all the models from their website-
also, I don't really understand their license
in my game these assets are used for the player to decorate their own room
Hello, I have a problem
I'm using Directory.GetFiles(Application.persistentDataPath ,"*.json"); to get the files names of my saves, to put them on list so the user can choose with buttons instead of having to remember the name of the file.
However, it doesn't return only the name, but all the path with :
C:/Users/AntoineEvola/AppData/LocalLow/DefaultCompany/SaveSystem\1.json for example.
Would someone know how could I get only the name, please ? :)
Yeah, the IO library has plenty of utilities for path manipulation. You're looking for Path.GetFileName(string path)
Thank you ! It helped a lot ! :)
Would you know by any chance how to check for new files created in runtime ?
Right now, it works but I have to restart the game for it to add the new saves to my list. :/
Thank's a lot !
Look into FileSystemWatcher, if I understand your request correctly
Listens to the file system change notifications and raises events when a directory, or file in a directory, changes.
https://docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=netframework-4.8
Can someone please help in sprite rotation?
8 Directional Sprite Rotation
I will share my screen in VC
arent you the one doing the save? you should be adding the saved item to your list before/after you write it to disk
Yes I am. I finally found where my mistake was, thank you :)
Hey guys i m optimizing my code when i see that
First and second picture.
But if i add my little part i got 3ms O.O against 0.9-1ms without my last part.
Any idea ?
2ms just for get value in array and 2 division and one distance just why ?
xD
by the way [j] have one thing in her array :/
AJAJAJA ! its vector3.distance xD add me 2ms
Distance calculation is expensive yeah, due to magnitude calculation, containing square roots
You can try with sqrMagnitude instead (that doesn't contain any square roots), and see if it improves performance:
if ((unscaled_p_viewer - unscaled_p_chunk).sqrMagnitude < radius * radius)
You of course have to take the differences in consideration, so that's why we square the radius
How are you profiling that? Stopwatch, and inside the editor? Bad idea, it doesn't take in account the CPU overhead and all the low-level complicated stuff.
If you need to measure performance, use a build and the Unity Profiler
Is it considered bad practice/bad idea to 'wrap' a singleton in statics?
public static void DoSomething(string foo)
{
Instance.DoAThing(foo);
}
// Called as
BarClass.DoSomething("");
// vs
BarClass.Instance.DoAThing("");
In my case it is a MonoBehaviour, so to add on to this, what about having a separate normal static C# class that calls the singleton methods/properties as this would remove all of the noisy of the UnityEngine.Object static methods.
I wouldn't consider it bad practice, but if that's just to "proxy" the instance methods with nothing else, I don't really see the use of it. Plus, it doubles the number of lines in your class. If you still want that, but want to lighten up the code, look into partial classes
how would you use partial classes to help in this case?
or is it just so you can define the functions separately?
One part that contains all of the instance stuff, and the other that contains the proxies
The use I see would be streamlining the use of the API, also shortens the code which makes it easier to read when used.
Oh you're doing an API, then yeah definitely make it easy for the user
Yeah sorry I should have been clearer. So having a separate class that is just a static proxy for the singleton is fine/good idea?