#archived-code-advanced
1 messages · Page 145 of 1
One consideration here is that your code path in the #else won't be run until you build, so it can lead to undetected compile errors. Sometimes it's kind of cleaner to use the boolean check instead (they're not that expensive). The preprocessor guards are necessary if you want to conditionally exclude a library completely, for example UnityEditor
That's true. I think I'll just try use funcitons for what's in the else if it's much of note. That way I'm running the same code with the only downside being a single funciton call.
Hey I have an advanced programming question, not unity specific, but I haven't been able to figure it out. I've been using a pattern that I want to identify. Not sure if it is some sort of state machine or something else. I 1st encountered this pattern in this GDC video: https://www.youtube.com/watch?v=tAbBID3N64A
I'm talking about the bark system. In the video they call it a self branching dialog tree, but say it could be extended to do much more. I have used this pattern to make a dialog system and a character controller. Then I wanted a name for it so did a lot of research and found Fuzzy State Machine which seems a good fit because you can have more than one active state at a time, however you can set it up as finite states and also add and remove states dynamically. The other system it sounds a lot like is a utility function, but rather than analyze the possibilities as floats and calculate the best choice, this system compares everything with bools and returns the 1st match rather than the best match.
In this classic GDC 2012 session, programmer Elan Ruskin shows a simple, uniform mechanism made for the Left 4 Dead series for tracking thousands of facts and possibilities, allowing intelligent characters to remember history, cascade from special to general cases, and select the optimal dialog, script, behavior, or animation for every situation...
Hey, first time using the IEnumerable.Where() method, did I do it right?
SaveFile[] matchingFiles = UnityEngine.Object.FindObjectsOfType<SaveFile>().Where(s => s.slot == slot).ToArray();
if (matchingFiles.Length > 1)
{
Debug.Log($"Length of files with slot {slot} is greater than 1.");
return;
}
Oh btw slot is a parameter that the function takes in public static void Save(int slot)
For one thing, if findobjectsoftype returns null you’ll get an exception. Aside from that, if you’re implementing a save system, how are you saving these assets at runtime in a built app? Like, if what you are retrieving are scriptable object assets you can make it work in the editor but not in a build. Sorry if I’ve gotten the wrong idea about what you’re trying to do.
Right now I'm only saving a single string; the player's name
Ok. But to where?
Ah the asset you’re loading is a text file. I guess you could load a text file this way but I would have expected file operations to be used. Good luck!
then use the unityengine mocks from anywhere
{
if (lookAt != null)
{
Vector3 dir = new Vector3(0, 0, -distance);
Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
transform.position = lookAt.position + rotation * dir;
transform.LookAt(lookAt);
}
}```
So I have this function that I am using on my 3rd person camera script. It is actually working fantastic for my needs, but I want to implement 1 quality of life improvement. Can someone please help my game start with camera facing behind my damn character? It just finds my object, and seemingly faces the same direction, no matter what way I move my character. Any suggestions or help would be totally appreciated
@compact ether Is lookAt starting out null or something?
where are currentX and currentY coming from?
those determine the direction of the camera
So I just came up with a solution that works for me. Basically I add an offset to the currentX input from my controller. It's not perfect, but it works haha.
The common way to save&restore is with JSON files. An easy way to do it for simple cases is with the built in JSONutility, see the unity docs. For more complex stuff people use Newtonsoft JSON which is free and available in the package manager https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@2.0/manual/index.html or on the asset store.
is it jsut me or does json utility not work with lists
for whatever reason
if i store a single object its fine but when i turn that into a list suddenly it just returns null everytime
and its really annoyinh
read the docs JsonUtility.ToJson
Note that while it is possible to pass primitive types to this method, the results may not be what you expect; instead of serializing them directly, the method will attempt to serialize their public instance fields, producing an empty object as a result. Similarly, passing an array to this method will not produce a JSON array containing each element, but an object containing the public fields of the array object itself (of which there are none). To serialize the actual content of an array or primitive type, it is necessary to wrap it in a class or struct.
i suppose i should make classes for things such as an item list
since i use that in both my inventory and storage containers
Yup, or switch to a more feature-extensive serializer like Newtonsoft.json, it handles top-level collections like any other type.
actually not sure about this
since then when i want to access an inventory item
instead of inventory.contents[1] id have to do soemthing like inventory.contents.contents[1]
and that doesnt seem right
i dont have the brainpower to do this lol
I'll check it out, thanks
Good to know, thank you
what happens if i make the distance parameter of BoxCast in unity2d to 0
Then you're better off just using https://docs.unity3d.com/ScriptReference/Physics2D.OverlapBox.html
Hello, I'm having mesh positioning issue and I can't figure what's causing it
Here the enemy(black square) is aiming towards player(red diamond) and you can see that I'm using this mesh as a field of view
I used CodeMonkey tutorial: https://www.youtube.com/watch?v=CSeUMTaNFYk
The origin position of the mesh has an offset and when I literally just copied the code of the tutorial I'd still have the same behavior.
I did google about it a bit but and found one solution that would make sense but it didn't help me
Link: https://answers.unity.com/questions/191774/meshvertices-position-not-correct.html
What could be the problem?
Have you checked if the enemy is not childed with an offset, probably not it but always have to check
I did and decided to keep the logic/mesh component on the main GameObject but nothing changed
O oke, so the fov mesh is not a separate object, is the fov mesh renderer on the enemy gameobject?
Yes, it's on the enemy gameobject
what is going on here
what is your gameplay objective
that screenshot doesn't look like anything
If you have it on a separate gameobject does it still have the offset from the pivot?
the codemonkey script is buggy
Mesh is rendering to the bottom left of the black box "enemy"
maybe use an asset store asset
The yellow is the field of view of the enemy(Black box) the start position of the yellow field has wrong position
you gotta understand the script otherwise this is gonna be tough
^
Yeah I do my guy
Hey I have animator overrides controllers created for each NPC. When the NPC gets spawned I am changing the animator runtime controller by :
anim.runtimeAnimatorController = Resources.Load<AnimatorOverrideController>("/ai_holder/_Animator");
Why doesn't the sprite change? Even though the override controller has the animations and sprites are attached to the animations.
Also the game is a multiplayer with Mirror.
I do understand it and it doesn't make sense that's it's not behaving the way I want
Could you send a snippet?
@junior sorrel this looks like a nice asset - https://assetstore.unity.com/packages/tools/particles-effects/smart-lighting-2d-112535
and covers what you want
is the sprite set by the overriden animation proerties?
and mi not sure if the loading of the animator will load the sprites too
the animator uses game object names as part of the paths to properties like sprites
it is likely the path name has changed because you have "(Clone)" in the path. using Resources here is odd
Looks like an epic asset but I'm doing a game jam, so won't pay for this :p
O are you making the mesh based on raycasts that return world positions?
Is this what you ment? I think it is set.
Yes, the simplest thing to do
i asked of in the animation the sprite is set?
mmm interesting
does it work if you dont load it from the resources folder?
It works if i predefine it before spawning in runtime
haven't tried not loading it from resources
didn't occur to me that it might be a problem
why does it say Sprite Renderer.Ai
that's really unusual
what is Ai
it should say SpriteRenderer.Sprite
really daamn didn't know that
it says that cause I have a code that makes the animations from the sprite library that I have 😄
okay
i think there's a lot going on with your setup
that's a little dubious
Thanks I hope this helps 🙂 @undone coral @humble onyx Thank you too 🙂
I am learning as I go and I try to automate as much as possible 🙂
okay
i think you should just set these up by hand for now
and see if it works normally
Not sure if I am doing things correctly but hey I got to learn 😄
if i set it up by hand it works fine
but there are loads of sprites and it just seem like a waste of time if you can make the computer do it for you 😛
Is there any way to run code for particular locales? I fired some events after comparing the current locale was equal to some locale assets. It works in editor but not in build. I think that might have been due to locales being addressables.
I tried saving and comparing the identifier strings but that did not work either.
are you using the localization package
Yes.
have you seen the localization package work in build for you at all?
Yes.
it sounds like you've tried the most obvious way to get this working
so i'm not sure
it should really be that obvious
as obvious at switching on the locale*
sounds like something else is busted
would someone be able to provide me an example of some code that would allow the player models head to move up or down depending on where the mouse is?
no, but if you provide us with the code you are writing to do that, someone might help you figure out problems you're having with it
well all i got is a FPS controller i've not started to try to do it
if you won't even try, why should someone else do it for you?
well i was just asking before i tried because i don't even know where to start for it but ill give it a go for now
it's hard to offer anything without more information about what you're trying to do. Do you want the head to literally move up and down to follow the mouse? Are you rotating it to look at the mouse? Is it connected to a body, and should look like it's bobbing on a neck? Is this 3d? 2d?
but that's why it's good for you to try first, because then you'll realize that you need to answer those questions (or at least can come here with something more specific)
ok thanks ill come back later once i have tried
nice, gl! 
it seems that AvatarIKGoal dose not contain the head just the hands and feet
so when trying to set the position of the head its not going to work
I'm basically trying to move the head up and down to follow the mouse
its a 3d head
You might not even need IK for that. Is it rigged or at least set up so that the head can be moved independently?
is it first person? third person? a picture is worth 1000 wordss
first person i want it to do this when you move the mouse up and down https://imgur.com/a/aWbqNQ2
so you've been saying all along that you want the head to move up and down, but you don't actually want that at all
you want the head to rotate
IIRC he sets up a LookAt IK controller in this if that helps https://youtu.be/UD6URb8aCco
if that's what it is then yes, sorry I'm bad with words I'm mentally a 7 year old
that's a weird thing to say dude
nah, i just can tell from talking to you that you aren't 7 years old 🤷♂️
give yourself some credit, we're all just trying to figure stuff out here
but it's worth it to try to be specific so that people can help you more easily
im trying my best im 17 and not been in school for 3 years
so with what you know about what I'm trying to do is there any possible way your able to help?
check out that video -- it will explain about what IK is (so it should make more sense) and he uses it to make his character 'look' at the right place like you are trying to do
the video got removed for me
you should still be able to click the link even with the preview gone
oof im blind thanks
there's also this https://docs.unity3d.com/Manual/InverseKinematics.html
looks like maybe the built in stuff supports LookAt objects out of the box? I haven't used any of this stuff though
But yeah, I think that's the right track. You want to use some simple IK to point the head, with the cursor as the LookAt target and see how that goes
well i don't get no error but just is not working
still don't work if its in its own script ```cs
using UnityEngine;
[RequireComponent(typeof(Animator))]
public class IKMouseLook : MonoBehaviour {
protected Animator m_Anim;
public Transform lookObj = null;
public float m_LookWeight;
public float m_BodyWeight;
public float m_HeadWeight;
public float m_EyesWeight;
public float m_ClampWeight;
void Start() {
m_Anim = GetComponent<Animator>();
}
void OnAnimatorIK() {
m_Anim.SetLookAtWeight(m_LookWeight, m_BodyWeight, m_HeadWeight, m_EyesWeight, m_ClampWeight);
m_Anim.SetLookAtPosition(lookObj.transform.position);
}
}
i set the lookObj to a cube and nothing
ok so i got it to work but its using Vector3 but i need it to be moving to where the player is looking
OnAnimatorIK takes a single int layerIndex parameter
not 100% sure that's important, but it should be added to check
In general functions with different parameter lists are considered different
add a Debug.Log() to the method to make sure it is being called
so its going this but insted if the vector3 it need to look at where the player is looking ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HeadRotatorBone : MonoBehaviour {
// Bone rotate vector
public Vector3 rot = new Vector3(20, 30, 10);
Animator anim;
// Bone stuff
//Transform head;
void Start () {
// get attached Animator controller
anim = GetComponent<Animator>();
//head = anim.GetBoneTransform(HumanBodyBones.Head);
}
void OnAnimatorIK (int layerIndex) {
print ("OnAnimatorIK - running");
// Convert bone rotate vector to Quaternion and rotate head bone
anim.SetBoneLocalRotation(HumanBodyBones.Head, Quaternion.Euler(rot));
}
}
what determines where the player is looking?
this i guess```cs
// Player and Camera rotation
if (canMove) {
rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
}
in that code, is transform the camera transform?
so you could just use transform.rotation in your call to SetBoneLocalRotation ? But this would be kind of weird, since if camera does a 360 spin, the head would also spin 360
if the animation is being rotated independently, you may need to divide outs its existing rotation
ok so its just looking straight down
even with this ```cs
anim.SetBoneLocalRotation(HumanBodyBones.Head, transform.rotation);
i) you're passing a world rotation to a function which requires a local rotation.
ii) even if you pass localRotation it wont work. you need to do the math (hint: lookup Transform Direction and Inverse Transform Direction)
take a reference point (camera presumably) add some offset to it. and then try to calculate the rotation needed for player to look at that point and apply the rotation
are you trying to make a character look at something, while doing its other normal animations?
no just trying to make the head rotate up or down when the player looks up or down
okay, same thing
its 3d and its first person
yeah
Let's create procedural animations using Animation Rigging!
► This video is sponsored by Unity.
● Learn more about Constraints: https://docs.unity3d.com/Packages/com.unity.animation.rigging@0.3/manual/ConstraintComponents.html
●GDC talk on Animation Rigging: https://youtu.be/XjMKbElVNmg
● Download the Skeleton: https://assetstore.unity.com/pa...
you definitely want to do this with animation rigging
there's also this - https://www.youtube.com/watch?v=hs2goLjUz4U
In this video you will learn how the Animation Rigging package can improve animation in your project via better tools and more flexible workflows. Discover how to setup a character, and harness both runtime rigging and animation authoring in this practical demonstration aimed at riggers, animators, and cinematic designers.
Speaker:
Ciro Contini...
the code you're writing is really far from working, this is already all in the animation rigging package
@past pendant is this helpful?
no because its nothing to do with the rigging the rigging is all done
you would move the transform
well, this is a rigging problem
i don't know what to tell you
you could have it working in 5-10 minutes with animation rigging
right now you're trying to solve for a bone rotation which isn't going to work
i was told to use IK
animation rigging be, place a transform somewhere along the direction the player is looking
well this is even simpler
because that time i linked you to
shows exactly what you want
in a brackey's tutorial, which means it couldn't be that hard
but that is looking at a object not what i want i want it to just move up and down when the player moves the mouse up or down
it's not looking at an object
it's using a transform as part of a solution to moving the head up and down
where's the object?
do you see an object in this tutorial video?
i don't know, 100% of your code is wrong
every single line
every single line here is wrong
so it's tough, you should probably use the animation rigging package
then everything will just work! 🙂
you're reinventing the animation rigging package right now, which is hard
you've made zero progress on that
you want to make the head move up and down? use animation rigging
you can place the transform you're looking at along the forward of the player camera in world space
that's it, the model will always look
i guess this is for making reflections look good?
would you be able to provide a code example?
// a reference to the transform
// you've configured via animation
// rigging to be the target of
// the head
Transform headTarget;
void Update() {
headTarget.transform.position =
playerCamera.transform.position +
playerCamera.transform.forward * 10f;
}
that's it
does that make sense?
do you see how much simpler this effect gets with animation rigging
ok i understand it kinda i don't get the animation part
headTarget.transform.position =
playerCamera.transform.TransformPoint(
Vector3.forward * 10f);
also works, it's the same
you have to watch the video
what the Brackeys one?
ok so i followed the video and its still not working
the head is just not moving
how do i create a highly modular COMBO system. without using mechanim
I used multi aim constraint just like how its shown in video. but im unable to move my target like brackeys does.
i hit play mode, my character looks at the target transform. but i cant move that transform at runtime (in playmode) at which the head is looking
How did you get the head to move mine don’t move at all
maybe there's something else moving your head.
try to disable all the head stuffs you have and check if you are able to rotate head transform freely in inspector
Yeah I can move it freely in the inspector but just not following the target
Does anyone know how to write this, so that it is compatible with 2020.3?
public IEnumerable<T> GetNodes<T>() => nodes.OfType<T>();
Apparently OfType is not available.
I wrote it like this, but apparently does not work exactly the same...
public IEnumerable<T> GetNodes<T>() => (IEnumerable<T>)nodes.ToList().Where(x => x.GetType() == typeof(T));
what is nodes?
If it didn't it wouldnt work on 2021
not necessarily
this is my code, btw
they may have added that interface to the type in 2021
can someone help me with this?
it happens in 2021.2.0f1 but it doesnt happen in 2020.3
What error do you get when trying to do this?
"does not run" meaning what? Doesn't compile? Throws some kind of error?
That strongly implies that Your version of UQueryState does not implement IEnumerable
If you ctrl + click on UQueryState to look at the struct definition in VS it will show you
yepo
Well, good news
it would have another , IEnumerable<something>
👍
Thanks for your help, mate
By the way, what do you think about my "other" solution, with the Cast function?
Idk anything about UIElements so I won't comment ¯_(ツ)_/¯
Anyone know some good tutorials for third person character controller with root motion?
Figured I might ask this here because it more toward c# as opposed to unity and is something that was hard to solve in the other code areas. For the purpose of convinience, are you allowed to create a list or array of variables that can later be assigned values?
For example if I have a for loop with I as the iteration variable, and I have an array or list of variable names, can I go like
listOfVariables[i] = listOfValues[i]
All the channels are for C# in Unity, this one isn't more "Csharpy". You were asked to clarify what you wanted in #💻┃code-beginner so my advice is you go and provide some detail
My bad thanks
I need some help i've been watching this video https://www.youtube.com/watch?v=Htl7ysv10Qs and i copy what he does but my head doesn't move anyone know why?
doesn't seem like coding is involved, so you may have more luck in #🏃┃animation ?
oh shoot yeah sorry
Maybe I have more success here. I am trying to have A List<Events> that contains different Lists like List<TeleportationEvent>, List<SubQuestEvent>. And then serialise it with JSON. My approach of having Events being a simple interface which TeleportationEvent and SubQuestEvent implement has not worked. Do you have a better approach?
I'm curious with this tips, where did you get it?
where the tips they says is that use unity animation events for things like visual or sound or other stuff. don't use them if your script is dependent on them.
I'm making a prototype with the same combo concept, based on animation event to determine when can the combo can be chained
In what way did it not work?
on the net
the question on this site. What do you think is it a good a to do this:-
I am creating a combo attack system. But i am not using any timers to chain the attacks to create a combo. Rather i am using unity animation event. For example:
Attack 1 has 5 frame animation.
On the 2nd frame of the animation i put an event that turns a bool called "attackChainable" true.
On the last frame of the animation i put an event that turns "attackChainable" bool false.
If i press the attack button when attackChainable is true i can transition to the second attack and so on and on. basically doing a combo. there's more to it but that is the basic gist.
But i read online where the tips they says is that use unity animation events for things like visual or sound or other stuff. don't use them if your script is dependent on them.
So, should i stop doing combo system that is dependent of unity animation event?
@fallen halo if that works well I think that it's a good way of going about it, your avoiding dealing with multiple checks and timers. Make sure the game can't be blocked/soft locked in any way if the animation stops before the bool turns off again.
You could also run a enumerator that adds and later removes attack types like an enum in to a list of some sorts and everytime you call attack you can check what current attacks are on going and continue a combo, this will also allow you to do multiple types of combos
are you aware of any tutorial for this
No, that's just what I came up with. I'll try quickly making it when I get home so you see what I mean
ok
How is mouse wheel supposed to be handled? (Old input system). When I scroll, the delta returned is either 3 or -3. I've heard from a friend that's the systems scroll setting, so 3 lines, but I don't know if that's true or how I would get that as a value to scale by. I could of course normalise it, but unless this can't actually happen, that would mean any time it registers something like a delta of 6 or 9, it'll get normalised as if it wasn't scrolled more than just scrolling to a delta of 3. Any advice?
Are merge conflicts inevitable?
I've heard that some teams keep track of who's using which files.
Is there an existing file lock tool for doing that?
Some version control software has a concept of "checking out" a file which gives you exclusive rights to modify it
I think Plastic SCM has this? Which is what Unity is replacing Collaborate with
Subversion has it too IIRC
Perforce has support for locking scene and prefabs in Unity too
git has locks now
merge conflict is not a bad thing
its just a thing you deal with, locking files that are not easily mergeable is common
I'm having trouble with OnValidate(). I can't have it run unless all gameobjects are loaded in the scene, so I created this:
protected async override void OnValidate()
{
base.OnValidate();
await Extensions.WaitUntil(() => SceneDetector.SceneIsLoaded);
SetPower(isPowered);
}
which successfully stops errors from happening when I open up the project INTO this scene where the script is. however, now I'm getting errors when I switch AWAY from the scene into a different one (where this script is not on any game object). how can/should I filter these validates? I'm already trying to detect if the scene is completely loaded using Opened and Open delegates in my SceneDetector class, but somehow that doesn't stop these errors.
PressurePlate is the gameobject with the script trying to validate, and it has a boxcollider2d
the error is definitely the base.OnValidate()
i think i might have just solved it by moving the waituntil above the base call, adding a timeout to the waituntil, and catching the timeoutexception (and then returning)
that seems to have done the trick
I have a question.
Let's say I have a card game and I'm casting a card. I have a CastManager that is in charge of managing the effects but sometimes the CastManager needs to prompt a player for something (like for example picking a target to deal damage to).
Any easy way of making an I/O system that's ambiguous to different types of prompts? Like does Unity have an equivalent to Java's Scanner.Keyboard or C++'s CIn?
I implemented a pop-up button box for players to click, I just want to wire the game to wait for users to click one of the responses.
Time.timeScale = 0```?
Or an UI object that covers all the screen, so it blocks events from reaching whatever's in the background
idk if they have anything built in, but you can code your own. For my character controller I use an abstract base class with a virtual bool method for the input so I can use anything as input, that way I use the same character controller for player or Ai characters.
C# has those yes but they are not suitable for an interactive graphical application like Unity.
@worthy sedge input in unity is not event based
it can be wrapped into event surrogate (most libs do)
So, I'm kind of stuck here. I'm trying to get the height of a wave based on an x position in Unity. I'm not using a shader graph for the waves so I don't quite know how to achieve this.
i.e. Rewired allows you to subscribe to input actions, so you can be reactive
same for new unity input system
in case you want to block the thread until it happens - no
the input polling is .. async? i guess
(also since hastebins no longer about, where would I put code so I don't dump 100 lines on you.)
Use the sine function
you need to let the game run, while you await the input. so in this case you must think in terms of simulation vs ui time
simulation time can be affected as @twilit hare said by Time.timeScale
setting it to zero and ensuring the game is using the deltaTime, will effectively suspend the simulation
Mathf.Sin, that much I understand, but I really don't get what inputs I need.
meanwhile the ui which should be using Time.unscaledDeltaTime will work in realtime
https://www.toptal.com/developers/hastebin/ugiduzikot.csharp
Heres the code, just not sure how I'd get wave height out of it.
they both run on the same thread, and blocking it is not an option
But does setting time.timescale = 0 make a script's method stop dead in the middle of processing? Let's say I called a function that has 10 lines of code but it needs user input somewhere on the 5th line of code. I'm guessing time.timescale won't stop the game from running the rest of the lines of code?
time is progressing each frame
but frames are time agnostic
time is an abstraction
its just a number handled by unity system that executes each frame
no it does not
whether the time is zero or not bears no effect on the game loop
It simply changes what Time.time and Time.deltaTime are going to be giving you in future frames
The only actual effect it has on the game loop is to make FixedUpdate run more or less frequently (in terms of real time), since FixedUpdate is called based on scaled elapsed time.
So in other words fiddling around with that may not be my best option here for me... I'm developing a card game which is a turn-based sort of game with a lot of UI game objects. For user input I was thinking of possibly using delegates but I wanted to see if there was a built-in thing that could make it to where I could stop a function from finishing until some form of input has been given.
I was hoping to save some time from hardcoding more functions 😅
you can use async
there are several implementations of async for unity, the c# async, UniTask, coroutines, and MEC (coroutine library)
Alright, I'll take a gander at those
there is also UniRx which should be familiar if you worked with js reactive approaches
this isn't what you're asking about, but for card games, scriptableobjects are saviors
yield a coroutine that does yield return null until the input is acquired, if that helps
or await Extensions.WaitUntil(() => YOUR_CONDITION_HERE);
Extensions.cs:
public static async Task WaitUntil(Func<bool> condition, int frequency = 25, int timeout = -1)
{
var waitTask = Task.Run(async () =>
{
while(!condition())
{
await Task.Delay(frequency);
}
});
if(waitTask != await Task.WhenAny(waitTask, Task.Delay(timeout)))
{
throw new TimeoutException();
}
}
Oh I know, they're helping me a lot with my card library 😆
I would also explore whether a callback with an Action would work for you. You make a gameobject/prefab panel and tell it to display itself with a callback to the handler.. bonus, if the user selects nothing (or cancels) then you can put the card back into their hand
So for example, I have something similar for a dialog box for a user to select a crew member for a given position. They click on the empty position, a dialog box pops up, and when the user selects a crew member, the dialog disappears and the callback is executed:
awaiting input definitely seems more jank than an event/callback
something's gotta invoke that callback
the input gameobject or whatever
if its a textbox run the callback when Enter is pressed
yea - new input system has event-based input built in though, so that might help
private SelectPersonPopup _selectPersonPopup = null;
_selectPersonPopup.OpenSelectPersonDialog(OnSelectCrew1Callback, Crew1.Person);
public void OpenSelectPersonDialog(Action<Person> callback, Person selectedPerson)
{
gameObject.SetActive(true);
.. and some other stuff ...
}
public void OnOKClicked()
{
gameObject.SetActive(false);
_callback?.Invoke(_selectedPerson);
}
nullable reference types 😍
If they ever implement NRTs in Unity (they actually have to switch to .NET and quit Mono), I hope it helps build safer code, especially for beginners and their NullReferenceExceptions
But in the state it's currently in, it's far from perfect, I would advise against using it
I can't imagine they will, that's such a major-impact breaking change because of their "special null", from what I understand
they do have NRTs in Unity
and I'm currently using them
On MonoBehaviours?
yeah
Oh, in the newest versions? With the #nullable enable and string? for example
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#nullable enable
public class PressurePlate : ColorDevice
{
[SerializeField]
private float offDelay = 1f;
private HashSet<Collider2D>? touching;
private SpriteRenderer? sr;
private IEnumerator? powerOffTask = null;
...
yeah
derp? I didn't think that was possible - I mean, I know you can force it to work by setting the language version or #nullable pragma but .. I thought it was guaranteed to break stuff
hm.. lemme try to find the page I was reading the other day about it
that's what i'm doing atm
I wanted to use the elvis operator for accessing a deep node without doing null checks "down the path" and gave up
ie something like:
you can expose the project properties, too
Heh weird it allows it, since even the docs advise against using ?., ?? or ??= on anything that derives from UnityEngine.Object
something = gameObject.transform.GetChild(0)?.GetComponent<T>()?.GetMember();
^ That works without the NRTs enabled
yeah unity does override the equals and null check operators stuff
so dont do those
'?.' on a type deriving from 'UnityEngine.Object' bypasses the lifetime check on the underlying Unity engine object
but it still helps point out where things can be null with the green underlines
yeah, I mean, it seems like .. dangerzone to use nullable referencce types when unity has overridden the == operator but I suppose it works? like if you set it to null yourself
saved me time, especially when dealing with code that runs in OnValidate()
since Start() doesn't run in the editor, obviously, things can be null all the time
NRT is just the compiler "doing more" so it outputs warnings on the null state of objects, and nothing else. It's not to be confused with the null-* operators
also i think it's just best practice to have the compiler warn you about things being null and making you think about it
it also helped remind me to parameterize my functions
which creates more modular code
But yep, I'm surprised NRT can be enabled with that "null-ish" state Unity introduces due to the object lifetime cycle
i dont have to null check a variable everywhere if the actually functions take a normal reference type, but then in Update() or whatever i use the nullable reference type field and do one null check
private void LateUpdate()
{
if(target == null)
{ // don't move camera if no target exists
Debug.LogWarning("Camera target not set");
return;
}
if(c == null)
{ // don't move camera if no camera exists
Debug.LogError($"No camera component on {name}");
return;
}
Reposition(target, c);
Resize(target, c);
}
so then I don't need to null check target and c inside of Reposition and Resize
before i used nullables, i didn't have parameters on those functions. still works perfectly fine, of course. I just like how it made me make the functions more modular and not assume as much
Yep, it sometimes makes the code more convoluted with all those null checks, but for good
You can't pass something that can be null, into something that cannot, without noticing
if you're doing the same null check in multiple places, especially if they are sequential (but in different functions) maybe you just need to make that function take a parameter instead, or make them work on the same null check somehow
exactly. it feels more diligent and safe to know that something could break
forces you to acknowledge it and handle it. what does it mean if this is null
Exactly, make the param not nullable, and do the null-check on the nullable one, one level above if you plan on passing the instance? multiple times.
❤️
private void SendPointRequest()
{
GeoPointExperience.TopLeft topLeft = new GeoPointExperience.TopLeft
{
lat = 10,
lon = 1
};
GeoPointExperience.BottomRight bottomRight = new GeoPointExperience.BottomRight
{
lat = 10,
lon = 1
};
GeoPointExperience.PinLocation pinLocation = new GeoPointExperience.PinLocation()
{
bottom_right = bottomRight,
top_left = topLeft
};
GeoPointExperience experience = new GeoPointExperience(pinLocation);
}```
Hey! It is interesting. I can not reach my "experience" object at all from inside of a function.
any idea? thnks
@mint sleet that's a private method
er wait
Are there any compilation errors in GeoPointExperience?
Not sure what we should be seeing there?
Hello. Is there a proven way to fix classes that may have become corrupted in the project?
I am trying to make an object to convert it into JSON
that objects uses different classes.
the structure is:
public class MatchAll {}
public class Must
{
public MatchAll match_all { get; set; }
}
public class TopLeft
{
public double lat { get; set; }
public double lon { get; set; }
}
public class BottomRight
{
public double lat { get; set; }
public double lon { get; set; }
}
public class PinLocation
{
public TopLeft top_left { get; set; }
public BottomRight bottom_right { get; set; }
}
public class GeoBoundingBox
{
[JsonProperty("pin.location")]
public PinLocation PinLocation { get; set; }
}
public class Filter
{
public GeoBoundingBox geo_bounding_box { get; set; }
}
public class Bool
{
public Must must { get; set; }
public Filter filter { get; set; }
}
public class Query
{
public Bool @bool { get; set; }
}
public class Root
{
public Query query { get; set; }
}
}```
@stable spear
and this is the constructor :
public GeoPointExperience(PinLocation pinLocation)
{
GeoBoundingBox geoBoundingBox = new GeoBoundingBox();
geoBoundingBox.PinLocation = pinLocation;
Filter filter = new Filter();
filter.geo_bounding_box = geoBoundingBox;
MatchAll matchAll = new MatchAll();
Must must = new Must();
must.match_all = matchAll;
Bool boolOB = new Bool();
boolOB.must = must;
boolOB.filter = filter;
Query query = new Query();
query.@bool = boolOB;
}
I can't make any sense out of those fragments. can you paste the entire file somewhere? (preferable a paste-bin like site)
Solved mine as well.
Need to remember to let all the methods get up-to-date game objects from scene :)
Hey guys, any tips on how I can control the movement of a cube based on where I drag my mouse?
Here's an example of what it looks like rn
The problem I'm seeing is when I drag from point X to point Y, it (mostly) is correct but it's not perfect. Sometimes it doesn't apply enough force at all, sometimes it does not go in that direction. Any pointers on how I can make this better?
How are you generating the force vectors?
@stable spear
{
Vector3 dragVectorDirection = (eventData.position - eventData.pressPosition).normalized;
Vector3 offsetDirection = new Vector3(dragVectorDirection.x + 0.45f, 0, dragVectorDirection.y + 0.45f); // adding offset since isometric. not sure if correct.
cube.GetComponent<Rigidbody>().AddForce(offsetDirection*magnitude);
}```
looks like you're converting the 2d vector into a 3d force vector without any real interpretation
Depending on what you want, there are many things you could do instead:
- Make the block glued to the ground so it doesn't rotate, and then slide it around the surface with the mouse.
- Project the mouse to a point on the floor (using Raycast), and then create a force pushing the box towards that point
- As the user moves the mouse, generate force vectors by raycasting the starting and end points onto the floor, and then taking the difference.
#3 is probably closest to what you have, but it would be more physically realistic
But maybe #2 is what you really want? I dunno. Up to you
No, not #2. Because I should be able to swipe anywhere on the screen, and it should be able to fetch me the direction vector in world space (endPosition - startPosition). The cube can be anywhere on the map, doesn't matter
Basically, if I swipe from the bottom right to the top left of the screen, a direction vector should be constructed that's appropriate to the game's world space and the cube should use that for the AddForce() call
what do you want to happen if the user drags the mouse around, but not on top of the cube?
do you actually want the cube to stay under the mouse as much as possible?
no, I want to apply a force of fixed magnitude on the cube, but direction is based on direction of swipe
You can use Camera.main.ScreenPointToRay to generate world-space rays corresponding to each mouse position
One more thing to note: I don't care about the Y axis. Ideally I will freeze position/rotation on Y
And then floorCollider.Raycast(...) to raycast those onto the floor
so the ScreenPointToRay calls to construct the vector3 must discard the y axis i think
(you need to get the floor's collider)
no..
ScreenPointToRay generates a ray in world-space. Imagine if the mouse were a little hand in the game world shooting a laser directly towards the direction the camera is facing.
A ray is a Vector3 origin and Vector3 direction
One you have that ray, you can cast it onto the floor collider
And get a point on the floor
that point will have y=0, assuming thats how the floor is oriented
Given two points on the floor, the difference gives you a force vector perpendicular to the floor
And it will be properly scaled for the perspective that the camera is in
so I need to call this twice?
yea
You could make a helper function so you only need to write that code once
The code that projects from the mouse position to the floor position
var c = Camera.main.ScreenPointToRay(eventData.position);
floorCollider.Raycast(b, out var hitInfo, 5f);
floorCollider.Raycast(c, out var hitInfo2, 5f);
hitInfo.point```
is hitInfo.point what I'm supposed to be accessing?
yes
you gotta handle the case where it doesn't intersect the floor
Actually, hm
In that case you can still do the projection, it just needs to be done manually. But you can try this to see if it works the way you want first
I just get a (0.0,0.0,0.0)
can I see your code?
var c = Camera.main.ScreenPointToRay(eventData.position);
floorCollider.Raycast(b, out var hitInfo, 5f);
floorCollider.Raycast(c, out var hitInfo2, 5f);
Debug.Log(hitInfo.point);
Debug.Log(hitInfo2.point);```
5f may be too small
you need to check the return value of Raycast
if either one returns false, cancel the drag (that means it went outside the floor)
yeah I get 2 vectors now
so now I get the difference of these 2 vectors?
yea
and that happens to be my direction vector that I use to move the cube?
sure. you may need to scale it by some number to get it the right magnitude
using AddForce, I suggest using ForceMode.Impulse
why ForceMode.Impulse?
I believe the normal AddForce is scaled by fixedDeltaTime first, because it assumes you are calling AddForce() every frame (every FixedUpdate). And thus if the framerate is different, it needs to be scaled
But a single big force applied to an object does not need that.
That's what Impulse is for
got it
So it seems to be working well but there's a small issue
After a while, both vectors resolve to the same value and thus no force is applied (because the difference is 0)
after a while?
let me send u a recording
do you see how after the first time I do this ,both the ray's vectors start resolving to the same valjue?
It looks like it isn't working cause the end of the drag is no longer on the floor?
if you're careful to keep the mouse over the floor, does it continue to work?
this can be fixed by replacing the floor collider projection with a manual projection
something like...
one sec
private Vector3 ProjectOntoFloor(Ray ray) {
float t = -ray.origin.y / ray.direction.y;
return ray.origin + t * ray.direction;
}
instead of floorCollider.Raycast do Vector3 bPoint = ProjectOntoFloor(b);
and same with c
that works as well 🙂
thank you so much for the help. times like these is when I wish I could tip someone on the internet with crypto or something
I should put a tipping address in my profile, heh. I wonder if that's allowed.
Which way should I go:
- Make an empty GameObject child and use it as a handle, supplying its
transform.positionin child component scripts - Make an editor script with
Handles.PositionHandle()as per https://docs.unity3d.com/ScriptReference/Handles.PositionHandle.html and use the serialised position field/property from the runtime script in other scripts
Those two things don't seem related at all. What are you actually trying to do?
Let's say I have a video and play it as a video texture. I know the video.FrameCount. How can I seek to a specific frame of the video ? Like let's say I want to get to the frame no# 50 of the video.
Oh apparently I can do videoPlayer.frame = 50 and get to the 50th frame.
Read again, I made an edit.
To rephrase: which is more lightweight, a GameObject or an Editor script?
probably the latter
Hmm, I'm unsure how you're saying it isn't clear; didn't you go to the link?
Here it is for reference, again: https://docs.unity3d.com/ScriptReference/Handles.PositionHandle.html
I'm familiar with that function. But I don't know what you're trying to do with it
Well, since it doesn't seem obvious – I wanna make a handle like you get by default for objects (the coloured axes with arrows pointing out that you can move around?) and use it.
You are writing an editor extension specifically?
You wanna do that in a build? Or Editor? Handles is a Editor only class
I usually make a child game object (for convenience and adjustment in local coord space) and supply its reference to scripts which need its position
Yes, just in the editor.
Well if its Editor only your concern shouldn't be "lightweight"
I figured out that it's not what I'm looking for since it sticks in the same place. In my case, I want to get a muzzle point for a gun to fire, which needs this muzzle point to follow the gun – easiest done with a child game object.
Oh, I do, I just tested it out
it's not what I want, as I said
One less game object is better, no?
One gameobject, in editor is a miniscule difference
I see. Okay, I'll not worry about it so much.
I have gone into a micro-optimisation route, which is quite novice of me 😥
If you're actually making a custom inspector on a custom component which specifies the muzzle point for a gun to fire, then it would make sense to use Handles to draw and manipulate the muzzle point, and store the value back in the serialized component
But if you're advanced enough to do that, I'm not even sure why you'd be asking this question.
It would be slightly more efficient than having an extra game object, sure
Yes, I would've made a custom GunEditor for my Gun and used it – really did it too, just a while ago.
This is the answer I was looking for.
There's also the part where I'd transform the point I got back from the Handles.PositionHandle in the gun's local space and all that but perhaps making a game object is just easier at a slight cost which I shouldn't even bother about unless I'm rendering thousands of guns.
Next time you gotta say what you're using it for. Otherwise, there's no way to connect the dots
I am guessing you never read my question clearly.
I did read it very carefully. It still doesn't make sense, by itself. It makes sense to you because you know what you're trying to do
Please correct me if I'm mistaken but I'd specified my requirement quite exactly here.
Alright, I should've given the use case and perhaps some code for clarity with the question.
Sorry for the trouble! 😅
hey does anyone know how to add test ads of unity in a game. please help if possible. There is some errors in the script i imported,
saying gameId and mySurfacingId not found in the current context...pls help!
this is a pretty common pain point for making touch interactions in 3d
i have a super polished version of this, and i can reference it in helping you
my #1 recommendation to improving your ability to implement a UI interaction like this is expressiveness. you should use unirx
cant you do that pretty simple with raycasting tho?
there are two ways that make sense to move a rigidbody using your finger - one is kinematic movement, and the other is to use a joint between the finger and the object
interesting last time i did up something similar i just updated the transform based upon a raycast from the mouse point to object
with kinematic movement, the object stays attached sharply to the finger, so it has good feel in terms of how it can be controlled, but you must interpret the finger movements, over time, to calculate a velocity (i.e. the momentum) to give the object you're manipulating
using a joint, the object feels like it's attached to the finger with a spring, so there's a "latency" between moving your finger and moving the object. the physics system naturally imparts momentum to the object this way.
@misty crescent does that make sense?
i think the user wants to flick objects with their finger
which sounds like a rigidbody
oh okay i only scimmed over the chat
it's pretty obvious from the video that the solution the user adopted is... bad
tbh 90% of the stuff i see in this channel is bad..
it doesn't behave naturalistically at all
it is a poor implementation of the kinematic movement option
so this is just the physics of how to achieve what you want. in terms of the parts, you have something that turns 2d screen positions into a 3d position of where the finger is ("raycasting"), and then something that turns those positions into motion ("physics")
there are a lot of approaches for raycasting
in my opinion, the ones that make the most sense are
- casting to a plane local to the object you're moving, like the local xz plane
- casting to a world plane, like the xz plane
- casting to a view plane, like the camera xy plane, at the depth z of the object
- casting along a custom built geometry of colliders, like an offset from a background cyclorama
there are a few more considerations: should it work with multitouch? what happens if the pointer goes off screen?
it's really tricky to do the raycasting right - you're turning 2d dxy/dt movements into 3d z-y-z positions, which has a really simple approach in math terms. if you don't know the math, you're going to introduce a ton of really nasty and frequent bugs, when the 3d position changes way more than the 2d movement does
you can use a word like "manifold" to describe this
a lot of really nice motions, like dragging something along the surface of a sphere collider, allowing it to go behind the sphere, is impossible to do without understanding what "manifold" means
you might also want to mix and match planes and colliders
here's the high level multitouch move code i use - https://gist.github.com/doctorpangloss/f215d5255d44fc9b913845681a9c6cce
i'm not 100% sure why unity doesn't provide these interactions. my feeling is they themselves do not know how to do them 100% right. they are really hard
I suppose there's always the question of how performant one can make that.
the cost is not measurable
not in my benchmarks
i don't really buy into a lot of performance woo. i don't think i've ever experienced a slow down caused by any non-rendering code i've ever written, ever, with the exception of maybe using Rayfire and a word game that had a large trie to load
over 10 years of doing this
Besides, in support of what you just said, I haven't thought of any use-cases where I'll be performing the 2D to 3D mapping calculation on several millions of surfaces at a time.
okay, and maybe one really, really weird interaction with nested coroutines, where if you use them, you lose a frame unless you iterate the IEnumerator yourself
yeah
i am advocating for help you design something nice 🙂
I agree. Btw the code you shared is with the UniRx framework right?
yes, but it doesn't do that much work
it's super high level
most of the knowledge in there deals with multitouch and moving the pointer off screen correctly
observe it does not use OnDrag for anything
it's so painful to do the move in OnDrag because pointers that move off screen and back on screen act weirdly
i use new input system which can also be pretty painful to deal with, but not that bad
yikes, not good for planning borderless window interaction
or like, just using it in the editor
this is good, I suppose
here's everything
i think the gizmos don't render right but everything else works
anyhow I'm not experienced enough to comment on that atm, haven't ever used this framework and I'm still quite a fledgling
🙂 it's okay
you can look at the source i shared and see some really small detail stuff
and some really big stuff
why don't you make your gist into a full UPM package repo?
it took me under an hour to make my first local UPM package, and the advantage of making it open source is significant
i think i'll have a small package as part of the software i write
to let you stream unity to phones consoles and computers
this is used as part of some other technology i develop
is that already a unity feature tho?
nope 🙂
swear it was with there mobile app
Unity Remote exists but I don't rely on it at all
last I used it (a few years ago) it left me wanting more
@undone coral looking through your github im guessing you had to use java for your college/uni as well lol
yep
<java-rant>
almost finished my last year of my bachelor got no more programming subjects haha just project management stuff rip
can't say i wanna use java more then i have to after this tho haha rather microsofts java
😆
@undone coral check this snippet for bugs: https://gist.github.com/doctorpangloss/afff3a44370e1cca18f5dd033dc48a71#file-raycastconstraint-cs-L179-L189
yeah you still need to fill in some stuff there
i think i always configure it completely
and rely on the assertions
to tell me what i forgot
until i write a real editor component
this will only work with new input system though
i also have no idea if it works with a mouse since the multitouch changes i made yesterday
it should, but it might try to work only with the right mouse button
it does not work with a mouse right now* @regal olive lol
sorry... i gotta fix that
just touch press control needs to be button control
yes, the Local Transform you take as an arg isn't being used
I also see a lot of bools, maybe you can use a flags enum instead
yeah
any button will do
anyway
someday i'll package it
i think this is more for learning
particularly how to drive a joint
looks good!
yeah it should work now, sorry about that
~~I'm doing some hula hoops with vectors and world/local positions, and just came across Transform.TransformPoint and InverseTransformPoint(). 
Are there any helper methods for "contains point" in transform? I couldn't find any. I can write my own, obviously, but I don't want to reinvent the (admittedly small) wheel again.~~
~~Hm.. it looks like I did invent the wheel a while ago, when I was first starting out. Is there anything that does this native to unity, or is this.. OK? I make no claims as to the quality/correctness of the below...
public static bool Contains(GameObject GameObject, Vector3 Vector)
{
Assert.IsNotNull(GameObject.GetComponent<RectTransform>());
Vector3[] leftV3 = new Vector3[4];
GameObject.GetComponent<RectTransform>().GetWorldCorners(leftV3);
float leftRectX = (float)(leftV3[0].x);
float leftRectY = (float)(leftV3[0].y);
float leftRectWidth = (float)(leftV3[2].x - leftV3[0].x);
float leftRectHeight = (float)(leftV3[2].y - leftV3[0].y);
Rect leftRect = new Rect(leftRectX, leftRectY, leftRectWidth, leftRectHeight);
if (leftRect.Contains(Vector))
return true;
else
return false;
}
```~~
Answered myself.. I think.
https://docs.unity3d.com/ScriptReference/RectTransformUtility.RectangleContainsScreenPoint.html
Hey guys
I have a question about Asset Bundles, If I have two separate projects, one for creating DLC (A) and the other the main project (B). Can I create an Asset Bundle in Project A and then, create a bundle. Then after creating the bundle, load it in Project B? Right now this doesn't work for me using Addressibles
addressables are hard to configure this way
the addressables pattern expects you to use the same project to create extra content, because it adds information to an manifest file that helps the client make sense of what is inside that particular group of files, i.e. the addresses themselves
what is the objective
anyway, you'd have to merge the manifests
this sounds fine
there's a really good sprite outline asset
in my opinion, when using assets or existing code is okay, it's #archived-code-advanced
The objective is to have a designer, work on a separate project and produce content that ends up in prefabs, like clothing. Then for my project to load that asset from the bundle
got it
i think just have the same project if you want to use addressables
I'm not savvy with the details, but we load bundles made from a separate project just fine into the main project
you can otherwise use the instructions from https://docs.unity.cn/Packages/com.unity.addressables@1.18/manual/MultiProject.html
maybe that'll work
@undone coral so it turns out that this works well with assetBundles lol
so I am gonna use that because addressable is pretty complex
and fails like 90% of the time
Is it possible to roll my own ECS system in unity without DOTS?
and by "possible", i mean if there will be a similar increase in performance
The main thing that boosts unity ECS performance is that it's jobified and compatible with burst compiler. Assuming you can implement these things yourself, sure. The real question is would you be able to do in a reasonable amount of time that, which took a whole team of professionals a few years.
And still isnt production ready 😆
Yeah..
Window / Analysis / Profiler
Then if it's in hierarchy mode, switch it to timeline
how to read this ?
Heya, I'm trying to use PrefabUtility.RevertPropertyOverride(), and by following what Unity Documentation says, I wanna get a SerializedProperty from a SerializedObject (which is a TMProUGUI)
I have my SerializedObject, but when trying to get the property with SerializedProperty textFont = serializedText.FindProperty("font");, it returns me null
When inspecting my object with the debugger that property exists but maybe am I trying to get it wrong ?
font is the property. m_fontAsset is the serialized value.
And for fontMaterial I guess it's m_fontMaterial ?
Thx a lot !
You can look at the source. It's in the package
I'm a hundred percent sure that my prefab's property is overriden here, and I'm trying to get rid of that override, but it just tells me that there's no override and it's doing nothing
Am I missing a hierarchy thing ? here's what I'm modifying
Hi! I'm looking to integrate Fastlane for the iOS build of our game. For that I need to be able to build from the command line, but have problems finding good docs and/or examples for how to do it with Unity 2020.x. We don't want to use the cloud thing, just build the project from the command line.
Apparently you need to build the project using C# code, but I can't find anything proper in the form of docs.
guys can anyone help me? i try to access a non static class from a static class. https://gyazo.com/344ecb7fe275806807fe94a25771c23e this is inside the static class https://gyazo.com/67cfca655a5f718b8452582bd789086c and i want to access ssm SkillSystemManager which is non static class https://gyazo.com/9c586c8e6f44c39eea315841d94b59c8
but when call the ssm it throws me a null error. even in a debug.log
i think its because i set Static SkillSystemManager ssm. what do i need to do in that case?
Have you ever assigned a value to ssm? If not, the error is expected
Friendly reminder that this is #archived-code-advanced, debugging should have been done before posting here
Same?
thats my complete methode
and got same null error
i think its because of static
No, it's because you never assign a value to ssm
It's not related to whether it's static or not
For future reference, "newb" and #archived-code-advanced don't mix together
Next time #💻┃code-beginner or #archived-code-general will be the best fit for that kind of questions
yea sorry 🙂
there are a people that only use ECS and/or DOTS, I haven't tried it yet, but it is finished enough to use for projects. I wanted to learn project tiny, but find that is complete mess still..
why would you want to? There are a lot of things you can do to increase performance, I made a free asset update loop manager that basically you call all your methods from one update. It adds in some efficiency and also using managers, like instead of each enemy having a movement script you have a movement director that controls all enemies, that will also add a lot efficiency.
Dunning-Kruger effect, someone with no advanced coding ability can't know there question isn't advanced 😆
Usable for projects and people experimenting with it does not mean production ready my friend. I will not put a single $ budget on it
there are already games released with dots
but if you find it too risky, you should definitely not put project time into it, like unity recommends
Bullet hell game
i am taking other measures too of course, but ECS could give a nice boost
I meant why would you want to write your own, would probably be a lot less work trying to figure it out in it's current form then start from scratch.
i enjoy lower level engine dev stuff tbh
yes, it's less efficient but also more fun...
also if you use a manager to control all bullets it should greatly improve performance, the classic unity methods would have a script on each bullet so that the more bullets you have the more performance hit you get, but managing them all from one script will eliminate that issue. I wish DOTS was a bit more stable and straight forward myself, but there is a lot of other ways to add efficiency.
between two unity projects you can also share a Unitypackage
you don't need to use assetbundles at all
unless this is a mod
if you just want someone to work on assets for you, that person can export the assets from their unity project by right clicking and choosing "Export to .unitypackage"
it sounds like you are only sharing assets at edit time
you wouldn't use asset bundles at all for that
or, share the files with visible metafiles turned on.
this is a pretty long journey. you can run from the command line and use -executeMethod ACSharpMethod.YouAuthor.ThatBuildsYourIOSPlayer
you can see this in the docs
fastlane is not easy to use, and you will discover that instead of hitting File > Build
you're going to be fixing fastlane at least once a week
because something changes about uploading to the app store every 60 days on average
on AVERAGE
imo, you will not save any time
if you don't touch your project for ~90 days, you should expect uploading to the app store to be broken
the prefab isn't overriden at the time you'e set the property, because you hvae no saved those edits
is my guess
Any thoughts here on GitFlow vs Trunk-based branch process? For context, I'm an indie but we're looking to hire 2 devs in the next few months and.. I want to get my house in order ahead of time.
(my current model is trunk based, tagging releases as they're finished)
@undone coral I have used Fastlane for other iOS apps, and there it's usually a matter of xcodebuild and some parameters to set the project to build. Simple. With Unity it's weird that I can't just build the project in a similar way, or at least export an iOS project that can be built.
It's the -executeMethod part that has me stumped. I can't understand why I have to write an app to build an app.
Can i clamp this so head wont turn 360?
Hello,
I have implemented in my Unity project leaderboard using CloudOnce
I added all the code and the sign in seems to work when doing an internal testing
My issue is that when I submit a score, that score doesn't show up thought when I check if there's any errors I would receive no errors and when I try to load leaderboard data I would receive nothing.
Anyone had this issue from before with CloudOnce or even with out it?
is this for a game?
there is a command line option to export an xcode project, it's called -buildTarget iOS, if you don't want or need to customize anything about the output
is your goal to get this to work in CI?
you will have to deal with licensing
merging .unity and .prefab files is tough
even when you set up UnityYAMLMerge
for games imo you should work out of a develop branch for everyone, and then merge into a master branch that is your current release. your external devs will not merge their branches, it's too difficult, if you accept you'll have to do that now you'll thrive
so gitflow.
additionally you should use your own lfs server, i suggest the one from here - https://alanedwardes.com/blog/posts/serverless-git-lfs-for-game-dev/
with github you run out of transfer bandwidth instantly
git on windows has bugs with files larger than 4GB
that link gives you an aws cloudformation stack you can deploy, relatively low pain, and you check in the credentials used to access your LFS server into the repo and it Just Works
to make merging easiest, i recommend working out of prefabs
@misty glade
especially for stuff like scene layout, i suggest a model of the form
Root Hierarchy
Level Layout Prefab
Sharping Prefab 1
Doctorpangloss Prefab 1
Sharping Prefab 2
...add'l prefabs
If I need to modify your layout, I would create a prefab variant and substitute it in the scene
hope that helps
those additions would be prefabs*
i have had no luck with the git asset store plugins
Cool - thanks for the feedback. I hadn't put too much thought into scene/unity work.. I was maybe hoping (dreaming?) that all the other developer work would just be in pure c# but.. maybe that's a pipe dream.
like for visualizing a difference in the scenes
It might still be doable for this project since the bulk of the work is on the C# side - the game itself is mostly lightweight UI
yeah another approach is to touch the scene as little as possible. it's fine to have scripts of the form
class MyScript : Monobehaviour {
public float somethingSerialized;
}
turned into
class MyScript : Monobehaviour {
public float somethingSerialized {get;private set;};
void Awake() {
// formerly set in editor
somethingSerialized = 2f;
}
}
it's exactly the same. nobody will need to modify those for singletons. for things that are genuinely instances it's painful
Yeah, that's my current "policy" right now. TBH I kind of hate working in the Editor; although it does make setting up the objects quite a bit more work
but for many scenarios you can set the values in the Instantiate caller, for example when spawning bullets
oh yeah
that's right
for UIs it's very similar, you want to use the scene layout pattern
prefabbing out pieces of the UI and encouraging people to create a new prefab for their additions and a variant for changes
really it's so you can merge
you still need to merge in this scenario, in editor instead of in the command line
In general .. my intent, were developers to be working in Unity, would be to make their own self-contained prefabs with scripts that accompany them
this is better. you need to visualize what people did
look at the prefab environment settings
In the .prefab files themselves?
if they're making e.g. cards you can make sure they get the right "editing scene"
Project Settings > Editor > Prefab Mode > Editing Environments
Hm, I'm not familiar with this/these settings.. will google up and brain download. Thanks.
Hm, OK. This is cool but I don't think necessary for our game. We're doing a lot of panels and cards (it's .. somewhat of a TCG) so the bulk of the work is in the C# - abilities, card interactions, etc. I still have to .. wrap my head around how I'm going to separate the work and integrate the results easily.
Perhaps this will be more relevant if we start doing art and/or content for each of the "cards" in our game that need specialized technical wizardry (particle effects and so on) - we could have a prefab environment "card template" and then each developer could be working on their own prefab (one card) within that scene
How can I wait for user input using async/await? I can only find examples with Task.Delay().
you can use UnityAsync which wraps everything sweetly for you.
You can use await While(Func<bool> something) or await Until(Func<bool> something)
this is really nice if you want to use TPL more instead of coroutines
Thank you so much! Didn't know about UnityAsync.
yeah I am using a mod type of system something that addressibles doesn't really cover
Yes, it's for a game, but not for CI. The idea is to get faster test builds out to the team by automating as much as possible using Fastlane and pushing to TestFlight. We have pro license of Unity.
I think I already tried that, and it's deprecated or doesn't work anymore.
im not sure if this is the right place to ask this, but is there a way to codesign or notarize something on a WINDOWS computer so that you can release an OSX version on steam? last i tried you needed a mac and had to get a special program i think
You still need a Mac
Or at least OSX
son of a b, do you need to buy that Xcode program as well once you do have a mac?
There are online services where you can rent a virtual mac for such purposes
XCode is free
You do need to sign up as an Apple developer though, which costs $$$ every year
Is this something i would only have to do once for a game? like if i kept releasing new builds, would i have to rent a VM every time
Sorry actually I misunderstood this all a little bit
YOu need a Mac if you want to build an app for iOS (iPhones) or for a mac on the Mac App store
oh, i should have specified my bad. my context is putting a MAC OSX build of my game on Steam
if you want to build a standalone mac player I believe that you can do that from Windows, but there are some weirdnesses with the filesystems, and it's actually a little simpler to do it from a linux machine
Or in WSL - see this thread https://forum.unity.com/threads/mac-unity-build-from-a-pc-not-opening-on-mac.947727/
So, a bit of information here. You could run MacOS in a VM, but Apple's licensing generally requires that you run MacOS (even on a VM) on Apple hardware. So if you're doing so for commercial purposes (and on the Steam store, I'd say that's yes), I'd be careful
Here's a relevant blurb from VMware: https://kb.vmware.com/s/article/1000131
Mac cloud rentals may be preferable if you don't want to have to buy the hardware
thanks for all the info so quick guys, ill look into these links
i've finally looked a bit at UniTask and now have discovered a fundamental aspect why NOT to use UnitTask. unitask does NOT use threads
That’s absolutely right. It only does async, not parallelism… but you can use UniTask.RunOnThreadPool
but because of that it also removes a lot of possible optimization of just plain async await. i don't see the point
it may only be useful if you are really only a beginner with async
it allows you to use the full unity API in async code without having to use coroutines
which you have to unlearn once you switch to normal async await
plus it has a better synchronization context than plain unity async/await
what do you mean by normal async/await?
imo it still has more drawbacks than usefulness. it's easier to work with for neewbies but it removes a whole aspect of async await AND you have to unlearn things when you want to switch AND your codebase can not easily switch to normal async await
What parts of the Unity API are not able to be used in async?
Probably too many to list all, but any notable ones?
all of them
but there is a caveat
if you do for example async void Start() and use unity api inside an await-ed method in there, you are NOT using threads either, so there will be no complaints from the runtime
but you should not do that anyways
why not?
oh, no i understood it incorrectly. no of course you can use unity api in async void Start() and yes, that will not run on the thread but THIS is behaviour you WANT and is normal behaviour
its actually not normal as far as C# is concerned, its actually kinda special behaviour
no, if you don't await an awaitable async method, this too runs synchronously
so that is default behaviour
and unity does not await async Start()
any source to back that up?
cause if that'd be the case, unity api calls should break
error message when you call stuff from outside the main thread is dispatched by the native engine in the first place, so it has all the power to handle custom sync with await any way it pleases
it just can't deal with a user running stuff explicitly in a thread the engine has no control over
wait, did you just change this again?
you should never use any unity api inside an awaited method. even if it's awaited from async Start()
but why?
because you want to DO work, OFFLOAD it and then APPLY it
thats something completely different
async is not for doing work
it is for synchronization of concurrent events
you know what i mean
you get something back that you waited for, return it to where it is needed and then apply it. don't apply it inside where you are waiting for it
ah, ic what you mean
afaik you can still build Mono without il2cpp for Mac. But I wouldn't bet on that. Just try a build and run it on some friends pc or some v cheap online vm
completely true. void cannot be awaited
the behaviour is similar to IEnumerator Start, which is not yielded at start
Don't know if this might help you or not, but you can wait for a task to finish in a coroutine.
while(someTask.IsRunning) yield return null;```
I've made custom yield instruction just for this purpose in my projects. I prefer Coroutines over async/await for easier control in Unity when it comes to MonoBehaviours
nah. it's not about a problem i had, just tangential referencing a previous discussion on this server. i hate coroutines. they are absolutely terrible imo. yes, they were a smart implementation of smth years and years back, but when async await was released it just superseded coroutines. that's why i am always against people telling beginners to use coroutines and in the discussion a statement popped up like 'if you want to use async await in unity you NEED unitask'. and no i said that that is nor was ever the case and now i just had a look at unitask and have reasons why you should absolutely NOT use unitask
btw. i'd like to make clear that i'm not advocating UniTask for everyone... it just does a lot of things like what malloc described in a neat package. If you know what you are doing, its probably best to use as few external libraries as possible. But i'd also be careful with blanket statements about the usefulness of UniTask and similar things. Maybe someone else finds them to be a perfect fit for their project.
sure, it just came up in the previous discussion where someone said you pretty much need unitask to do async. and sure, maybe unitask fits perfectly for someone and their project. just, when you want to get over the beginner programmer status, which i expect everyone to try to accomplish, i would argue that things like coroutines and unitask will hurt your (personal)development
i dont see what that has to do with someone being a beginner or not
to make informed decisions, it is best to understand all available options
of course. but that does not mean that you should first check each and every thing before going with the standard approach which fits / works for 95% of all applications
probability is high that if you think the standard approach won't work for you, you may be thinking about your problem incorrectly
yes, very much so
btw, the reason why unitask was advocated so strongly in that original discussion was because unity does a Thread.Sleep(1) every time an async thing is scheduled, which may lead to unexpected performance degradation in some situations.
You can read about UniTask's justifications in this blog https://neuecc.medium.com/unitask-v2-zero-allocation-async-await-for-unity-with-asynchronous-linq-1aa9c96aa7dd
Which also makes it clear if its restrictions and ideals are for you
however that article does not discuss the threading issue that was the origin of the discussion. one might argue threads are just one way to implement async/await... but some have come to expect threads, and potential offloading to a different cpu-core, as something integral to async/await when used together with regular Tasks. UniTask relegates the Threadpool to one method and presents it as something dirty and wasteful.
Luckily in those cases you can still use plain old tasks. I'm mainly linking the blog for the more reductive statements made earlier about x and y. It's easy to just read the blog, and see why some of that exists, and that can be used to make decisions about whether or not you'd want to use it over another implementation.
I'd argue that most standard usecases for coroutines (which UniTask is mainly aiming to replace) are not necessarily actually being used to offload 'work', and are instead just being used as a cleaner way to represent program flow. If you want to actually perform work then I'd probably not recommend it.
Got it. I can share my script sometime tomorrow. I feel you, I use fastlane the same way.
Yes, there is a code signing utility on GitHub that is compatible, is my memory. Did you try searching?
I advocated UniTask so strongly because it offers some great semantics for games, where sometimes you do stuff that can be in the background, and sometimes you want to do stuff that’s Unity main thread only, and it provides a super elegant way to switch between the two contexts within a single async method
Well, that would be most awesome!
Can someone help me in integrating solona wallet in unity? I can't find any docs related to it.
Hi. Does unity scenes/assets have a hash that changes when the scene/asset changed?
I don't think so.
maybe it does. git internally uses SHA-1 of files to track file changes. maybe unity does that at startup and then combine it with FileSystemWatcher after starting up.
if you want to somehow retrieve that hash, i'm not sure how. maybe you can find something useful in Library folder
mhh thanks for the hint, looking into it
also, i have seen in tutorials for 2d they draw a box collider every frame of the attack animation.
will it be any problem if i just do it in one frame of the whole animation with animation event. not using box collider but using a function that draws a overlapboxall
overlapboxall will allocate a new collider2d array everytime its called. you can also go with Physics2D.OverlapBoxNonAlloc which doesnt do any additional allocation.
but as for hitbox, no one can really help you with it, because there are too many other factors influencing it
Hey all, I'm having an issue with texture quality. Essentially my textures get quite pixelated when I change the resolution of the game window (happens in build too)
After some testing it seems it is due to the textures import settings being set to a value much higher than what is being displayed. For example, the render texture is 2048x2048 and when I change the resolution from 1920x1080 to 1280x720, it gets very blurry and jagged edged. Changing the texture size to 1024x1024 during runtime fixed this issue, but then looks poor for higher resolution displays. Is there an easy way to automate this? Otherwise ill just do it through code
I might be misunderstanding your problem, but do the textures have mipmaps? (e.g. from enabling Generate Mip Maps in the import settings.) If not, see if enabling that fixes them.
They dont - this is what they look like
the latter e.g. the normal texture works, but not the render texture
Generating mip maps on the resource textures is worth a try, then; that will automatically generate smaller versions of them and the shader should intelligently pick the most appropriate size when rendering.
a 4k texture looks great for HD displays, but this is software and a 720 display is not unheard of. Thus the render texture would need to get dynamically resized to avoid the downscaling which I think is the cause of the bad pixilation (as changing it from 4k to 1024x1024 when I resize the view works)
oh, ok - lemme try that
I thought that was based on distance and had nothign to do with UI resolution
As I understand it I think both should affect it? As far as I know it will pick a mipmap level according to how fast the UVs are changing in screen space, which will be higher if the texture is closer to the camera or if the screen is higher resolution.
But it's possible I'm misremembering how the samplers work.
Yeh you're right - seems that was exactly what was happening
didnt have samples so it was trying to run some downscaling I imagine?
thanks for the help - ill research more into how this stuff works
Just want to confirm: If I use GetAssetBundle() with a version number, and save the returned assetBundle, when I access that returned bundle am I accessing it from RAM or disk? (a blog seems to say Disk)
Secondly, should I cache any files I get when I use bundle.LoadAsset() or is LoadAsset's speed negligible and I should re-load each time I try and grab the file? (Basically does LoadAsset decompress - and should I clear this cache on things like scene change?)
what is your objective
is this for mods?
No, its for android mostly, but for patching and to reduce initial build size
I don't see how that matters though, those Q's answers should have general best-practice answers
the behavior of GetAssetBundle() in terms of disk versus memory isn't specified in the docs. should it matter? the safest assumption is that everything that implements IDisposable is definitely in memory. you can also probably assume that anything that's a GameObject or derives Component is also going to be in memory. on android, the asset bundle is decompressed on a background thread; i don't know if on android it deserializes on the background versus on the render thread
the best practice is to not use asset bundles for those purposes, use addressables. anyway patching outside the play store is rarely worth it - there are only 100 games in the whole world where it may matter.
@fervent sage GetAssetBundle() will save the asset bundle to disk, notify you, and then load asset will decompress and deserialize
Well for a TCG, patching has a non-trivial file-size so I'd rather split it up.
So I can do the same thing for desktop
AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(unityWebRequest); will decompress and deserialize to memory, you will not want to call GetContent twice
yeah that's fine, but what I saw a blog post seem to imply, is that bundle here is saved to disk not memory
unity web requests are disposable, so you will also have the asset bundle bytes in memory, but they will be not useful to you? i'm not sure
i wouldn't over think it
it sounds like it can give you some of the asset bundle's contents on demand, earlier than completing the download
that's what it sounds liek the purpose of all of this is
i mean, why unity made this API
sure, and for addressables, I just went with bundles because there were much better tutes on bundles but no good ones I could find for addressables doing what I need (reducing android initial build size)
for "streamed asset bundles"
kk
is it mostly images?
like card illustrations
is that 100% of the assets you want to download
Thats what takes the size (and audio tracks) but I ended up using it for all the data in resouce folder
i understant it could be scriptable objects or whatever
okay, i would personally recommend just zipping those and downloading them, and updating the rest of the game via google play
asset bundles are very painful
That seems exactly what asset bundles are for
they just boil down to another binary, adjacent to google play
sure
i'm saying they are sort of radioactive
I've already implimented the bundle method so ill just go with that. What do you mean radioactive?
it's better to just have your game not start until it downloads a zip file, unpacks it, and you load the images. and if you need more zip files, you can update the list of URLs and push a google play update
you don't want to stream this stuff, and you will never want to define e.g. the cards alongside the images
it will be radioactive to store anything but the images in the asset bundles, and then once you are only storing the images, you're reinventing a file system to reference them (like, what is the name of the sprite in the asset bundle and blah blah blah) - you will have just been better off getting a big dump of images
it's not useful to have a setup where you have broken references that aren't fulfilled until a bundle is downloaded
because you would have no way to tell the difference between that and a bug
like, a card missing its image
ah nah I sorted all this already so all good there. My cards are dynamically generated from a string of card data I pull on game start, so I won't have those random things likely
Uhu, well thanks
Hey guys! Quick question. My team and I are currently making a game (on the blockchain) and we are facing an issue/bug. Whenever a person logs in (with MetaMask), they can log in again and pretty much play on 2 + screens with the same login. Is there any way to differentiate/limit them to just one instance?
use this package https://github.com/attilioHimeki/unity-build-tools/blob/master/CommandLine/build-batch.bat
there's also a package called Trimmer
you can author your own build method too:
static void Build() {
...
var buildPlayerOptions = new BuildPlayerOptions()
{
extraScriptingDefines = new[] {"UNITY_ASSERTIONS"},
locationPathName = destinationPath,
scenes = EditorBuildSettings.scenes.Select(s=>s.path).ToArray(),
targetGroup = (ios build target group),
target = (ios build target),
options = buildOptions
};
BuildPlayerWindow.DefaultBuildMethods.BuildPlayer(buildPlayerOptions);
}
etc etc
Isn't that pretty straightforward? When you get a login request, check to see if they're already logged in and if so, log them out?
(or deny the second login, whatever makes sense for your situation)
Yes, that's what we also thought, but how?
hey can anyone tell my how i can do GameObject array in custom window editor?
ok so this has nothing to do with unity, but i know that it is used in unity a lot.
how can i get all workshop items, from a specific person (the active user specifically), and a specific game
i am using Steamworks.NET
my first idea was to go with something like this
UGCQueryHandle_t handle = SteamUGC.CreateQueryUserUGCRequest(SteamUser.GetSteamID().GetAccountID(),
EUserUGCList.k_EUserUGCList_Published,
EUGCMatchingUGCType.k_EUGCMatchingUGCType_Items,
EUserUGCListSortOrder.k_EUserUGCListSortOrder_TitleAsc,
AppId_t.Invalid,
SteamUtils.GetAppID(),
1);```
but i don't have much experience with Steamworks and how it works
// OPTION 1
SteamUGC.GetQueryUGCResult(handle, 0, out SteamUGCDetails_t details);
// prints all details out
// OPTION 2
SteamAPICall_t call = SteamUGC.SendQueryUGCRequest(handle);
onSteamUgcQueryCompletedCallResult.Set(call);
//onSteamUgcQueryCompletedCallResult just prints the callback
these are how i was trying to receive the results, but neither of them gave me what i wanted.
Maybe I'm assuming that you're handling more of the backend then you are.. I don't know anything about "MetaMask" unfortunately... questions about how a specific library works aren't likely to be answered successfully in this discord, unless those libraries are pretty commonly used in the Unity universe, I suspect. It's certainly the first I've heard of it
nvm i figured it out
i had to use both
i queried option 2 till i got a result, then i run option 1 and it gives me what i want
Hi again, so lately I've been trying to work with a KdTree in order to paint the vertex colors of my mesh, I'm using a kdtree to get the nearest vertices when my character collides to set its vertex color, that I then process into a shader to display the right textures for each vertices, but the behaviour I am getting is strange, it seems it only takes 1 out of 2 vertex which gives some kind of "strips" effects :
here is the kdtree : https://pastebin.com/AjNszEGx
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.
My mesh coloring job : https://pastebin.com/dMbaeFer
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.
My scripts that get the vertices within a "radius" : https://pastebin.com/vXPH3KNZ
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.
and finally my function that is called on Collision enter to set the vertexColors : ```public void SetWound(Collision collision)
{
if (collision.contacts.Length == 0)
return;
bool b = false;
if(part == Part.HEAD)
b = true;
int[] vertices = ragdollController.pointVertices.GetClosestVertexIndex(collision.contacts[0].point, coloring.renderer, 0.0015f, b);
coloring.woundedVertices = new List<int>(vertices);
coloring.UpdateMesh();
coloring.LateUpdateMesh();
}```
I think that the issue my be coming from the findNearestsK function in my KdTree.cs, more specifically because of the selector that either checks for the closest x or y value of my vertices, but I just can't get it to work to select ALL the closests vertices within range, how would I do that?
to cut it short, how would I find the vertices of my mesh within a radius using a KdTree/Octree?
if someone has an answer, please ping me
using an existing octree implementation for unity
it's sort of unnecessary for what you're doing though
you should retrieve the vertices by projecting and querying the UV map
How would that be doing say, on Android platform with a mesh of roughly 6000 vertices ?
I mean performance wise
Lookups shouldn't be slow (assuming correctly configured tree)
Generation might be a bit slow
No the search is really well optimized especially for Android, the thing is, it just doesn't pick up all the vertices within an area as you can see in the picture
I am kind of a mess when it comes to mesh manipulation, could you provide an explaination on how would I retrieve the vertices using the uv Map? Is it expensive? Because it would kind of defeat my initial purpose that is not to loop through all the vertices using kdTree
MetaMask is not really a library, it's a cryptocurrency wallet (browser extension). We are using a WebGL build. Do you know any Discords that could help out?
That package hasn't been updated for 2 years. Are you using it? My understanding is that command line building and building in general has changed a fair deal lately.
You have a source for that info?
Sure there's the "new" build pipeline
But it's not that much different, especially if you're not doing anything fancy
This one is also old, it talks about -profileMode which doesn't seem to exist anymore.
@flint sage No, I don't know when and what has changed, but many articles talk about using -profileName and that option can't be found.
I've never seen an argument called profileName, chances are it's somethign custom
Could be. So much about Unity is about installing this and that extension.
It's not but okay
What I'm trying to do isn't exactly rocket science. It's getting iOS and Android builds from the command line.
You just gotta create a static method that calls BuildPipeline.BuildPlayer and then use executeMethod commandline arg and buildTarget
Hm
why hybrid renderer can render big scene open world scene ?
@flint sage That's more or less what I've done.
public static class Builder {
static void PerformiOSBuild () {
BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions {
scenes = new[] {
"Assets/Scenes/LoadingScene.unity",
},
locationPathName = "iOSBuild",
target = BuildTarget.iOS,
options = BuildOptions.None
};
BuildReport report = BuildPipeline.BuildPlayer(buildPlayerOptions);
BuildSummary summary = report.summary;
}
}
Hmmm... Can't a regular render do the same?🤔
% /Applications/.../2020.3.19f1/.../Unity -quit -batchmode -projectPath /Users/chakie/Work/... -executeMethod Builder.PerformiOSBuild
Gives no output and errors, except a notification is shown that it failed due to compilation errors. I try to find something in ~/Library/Logs/Unity/ but nothing there refers to a compilation. The timestamps on the files are all from when I ran the command though, so it's the right place.
Pass -logFile
Also, sometimes weirdly enough unity doesn't log the exceptions. Probably because it already knew it was broken
You can try deleting library/scriptassemblies
I nuked all the log files and now Editor.log is current.
using UnityEngine;
using UnityEditor;
public static class Builder {
static void PerformiOSBuild () {
var buildPlayerOptions = new BuildPlayerOptions {
scenes = new[] {
"Assets/Scenes/LoadingScene.unity",
},
locationPathName = "iOSBuild",
target = BuildTarget.iOS,
options = BuildOptions.None
};
var report = BuildPipeline.BuildPlayer(buildPlayerOptions);
var summary = report.summary;
}
}
Gives:
Assets/Scripts/Builder.cs(8,38): error CS0246: The type or namespace name 'BuildPlayerOptions' could not be found (are you missing a using directive or an assembly reference?)
Assets/Scripts/Builder.cs(13,22): error CS0103: The name 'BuildTarget' does not exist in the current context
Assets/Scripts/Builder.cs(14,23): error CS0103: The name 'BuildOptions' does not exist in the current context
Assets/Scripts/Builder.cs(17,22): error CS0103: The name 'BuildPipeline' does not exist in the current context
Seems ok to me.
I mean yeah...
waht did you expect
You have to put editor code in an editor folder/asmdef
I had no idea I should expect that. Ok, now I know where to start reading up.
@flint sage @undone coral Got my build working now and Unity seems to have created a valid iOS project. Thanks for the help!
The thing I wasn't aware of was the "editor only" asmdef.
Hey! Just set up a mobile AR app. Used only standard AR assets by Unity. Simple plane detection + object spawning. I've set up the forward render in the graphic settings and described the camera usage.
AR functionality is working, planes getting detected and spawning works. But the camera feed stays black. I've checked the default AR camera and it's rendering to a solid black color. Is that on purpose?
Hi, i'm writing unit tests with the unity test framework and one of my tests loads a scene, the problem is, if i load the scene the playmode test stops and the scene i just loaded is played. Is there any way to make a "don't destroy on load" play mode test?
https://www.toptal.com/developers/hastebin/exipuyonop.properties can someone help me add to this script to where each gun selected can have its own stored bullets array but then the current gun has its bullets array stored in a bullets array so it can show what bullets are left when a gun is selected. Cause i current have a bullets array show what bullets left but it shows the same bullets left for all guns.
have you tried using DontDestroyOnLoad?
How can i do it? The game object with the play mode test manager is created at runtime
i can't add a component to it
DontDestroyOnLoad is a method you call on objects, not a component you add to them.
Here's a thread discussing this https://forum.unity.com/threads/play-mode-tests-scenehandling.751049/
Well i know but test classes aren't monobehaviours so i dont have that method available.
DDOL is a static method
the question is do you have a way to get a reference to the object you're trying to preserve to call DDOL on it
If all else fails, I assume GameObject.Find would work to do so.
could be perceived as hacky though
I've had this idea, but it would be really hacky, i'm gonna try it out anyway
@sly grove are you able to help me a sec with my problem if it not too much trouble
From #📖┃code-of-conduct
Do not: @ people not in the conversation. Use common sense here, please.
Discard if that's a followup to an already existing conversation.
sorry
or you can save the instance to a static field. ddol static unity objects can be accessed anytime anywhere even after scene changes
If I use this:
UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(info.bundleURL, info.bundleVersion, 0)
Is there a way to see if the request was fulfilled with the cache or by downloading?
using this Caching.IsVersionCached you can determine if the asset was previously cached. if previously cached, it will load from cache
mk thanks
Hmm, it wants me to use the version with a Hash apparently the int version one is depreceated; I am caching with a version number though so I want to use that. Is there a non-depreceated method to do this?
Need some help with Visual Studio with unity on Windows, my project loads just fine on vs code or in visual studio on the mac machine, however, for some reason, only this project i'm working on, whenever i open it via visual studio everything is with red lines, not even basic types such as System.Boolean is found
never had any similar issues, thoughts?
i'm not sure. Hash128 is something you could get from the manifest aswell when generating asset bundle. generally you should use that instead of the integer version for GetAssetBundle method
i) its not related to advanced-code even remotely.
ii) you should probably configure your ide #854851968446365696
How can I make an animationClip with 4 box colliders with diferent offsets and sizes by code?
I managed to create animationClips by code for spriterenderers but i don't know how to make that for Boxcolliders
ObjectReferenceKeyframe .value doesn't work with the vector 2 of the offset like works with a sprite for example
I am testing downloading my assetBundles from Git in my editor but get the error:
** - The AssetBundle 'my URL' can't be loaded because another AssetBundle with the same files is already loaded.**
I assume this is because the assetBundles when built are somehow already loaded, but I can't seem to see any way to exclude them from the build?
I am using the AssetBundleBrowser
^ This happened on the first play and on none after. Will need to see if this will be a persistent problem on new builds or something
if you still need help, message me directly