#archived-code-general
1 messages ยท Page 68 of 1
oh well my implementation just changes the speed of the audio playing taking into account its base tempo and corrects the pitch
since I want to incorporate all sorts of different songs I can't just globally change it
has to be per stem
oh wait would it be better to store all the stems at the same bpm/key and shift it globally actually?
might be bad for audio quality but I doubt many people would notice
Would https://docs.unity3d.com/ScriptReference/AudioSource-timeSamples.html be a better approach? I know you mentioned this above
machine created humans so it can create itself
actually yeah I think, I just have to make logic for when the audio track that controls that stuff gets swapped out but once I do that it'll probably be better
thanks!
Alright, now i feel silly. How do i raycast on a UIelement?
or get whatever the mousepointer is currently hovering?
using the built in Event System
var eventData = new PointerEventData(EventSystem.current);
eventData.position = Input.mousePosition;
var results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventData, results);
if(results.Where(r=>r.gameObject.layer == 6).Count() > 0)
{
Debug.Log(results[0].gameObject.name);
}
using this?
wait, did i forget to set the layer..
noo, thats not it.
Tip, you can shift the lambda in the Count, and get rid of the Where
what? like this?
results.Count(r=>r.gameObject.layer == 6) > 0
Yup
is the code running?
it is indeed running
well okay, now it worked
sigh.
i swear, this place is great if you wanna make yourself feel silly
whats the difference between ?
EventSystem.current.RaycastAll(eventData, results);
GameObject.Find("Canvas").GetComponent<GraphicRaycaster>().Raycast(eventData, results);
this might be a really dumb idea but what if I had a blank audio clip that I just used as the "master" audio clip that I can sync everything else to? I'm only working with 32 bar (128 beat) loops so that could be the main controller
I just figured I should run the idea by you first
https://docs.unity3d.com/560/Documentation/ScriptReference/EventSystems.EventSystem.RaycastAll.html
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-GraphicRaycaster.html
Based on the docs, it seems like the EventSystem is global, and will use any and all raycasters base (which GraphicsRaycaster uses), while GraphicsRaycaster is specific to only checking for events on the Canvas its attached to, the only scenario I can think of is if you have multiple Canvases layered infront of eachother, you may also have multiple GraphicRaycasters for each canvas, you could use the graphic raycaster to check for hits on one canvas and not the other, or if you just want to know if there is any hit regardless of the canvas it belongs to, maybe the EventSystem makes more sense, but this is just a guess as I havnt had many use-cases for this myself
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
ah splendid, thanks!
I have this purple emoji, green circle and white door sprites with the emoji one being placed in front of all other tho not by much. By only 0.01 or so. Sometimes emoji gets rendered UNDER the other two. Any ideas how to fix it?
It's a photo from the side
Assuming the hashset only has one member, how do i get it?
HashSet<Unit> selectedUnits = new HashSet<Unit>();
//Some code to add units bla bla
if (selectedUnits.Count == 1)
{
infoPane.transform.parent.gameObject.SetActive(true);
string newInfoText = "Name: " + selectedUnits[0].name + "\n" +
"Faction: " + selectedUnits[0].faction + "\n" +
"Role:" + selectedUnits[0].role.ToString() + "\n" +
"Health: " + selectedUnits[0].hitPoints + "\n" +
"Damage: " + selectedUnits[0].attackDamage;
infoPane.text = newInfoText;
}
hey,
is it possible to check if pointer is still hovering over a button or not ?
try this
Not sure what you are doing. But in case there is no "IsHovering" property or whatever, you can always set a boolean to true when pointer start hovering, and then set to false when it stops.
which handler is responsible for the pointer hover ?
?? some parts of the documents are missing in 2021 ??
I have version 2021.3 and it does have the Ipointer under UnityEngine.EventSystems
its weird the the documents has no reference to the UnityEngine.EventSystems for version 2021.3
the UI docs are separate
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/index.html
Thanks !!
but I still couldnt figure out how to check if pointer was still hovering on the button after clicking
Is it possible for a unity game to load and execute an assembly not built directly against the unity .net dlls but rather against some other .net standard profile ?
which event I need to run to see if the pointer is on the button ?
IPointerEnter and IPointerExit
yes but those wont run after u press the button
unless u exit the button then reenter
I don't really know much about it, but isn't there an property in the mouse event data for checking if it's a drag operation and what entity is handling it?
probably friction. of course you haven't provided enough info to actually know for sure
{
var normal = Quaternion.FromToRotation(Vector3.forward, player.hitNormal);
player.velocity = Vector3.ProjectOnPlane(new Vector3(0, player.velocity.y, 0), player.hitNormal);
}```
fyi im using a character controller
{
player.velocity.y += player.gravity * 3 * Time.deltaTime;
}
else
{
player.velocity.y = -2.5f;
}```
the one on the right slides down fine
but the left one is so slow for some reason
because if i try to increase the speed multiplier in velocity.y it goes down the other too quick
so how do i fix this?
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.
heres the script
wouldn't you want to store the current gravity value in a separate float then use that when creating the projected Vector3? because as it is now you're resetting the x and z velocity every time you project the plane
hmm maybe
ok i think i got it to work, now i need to figure out how to make it so the player can't push against the slope to slow down the sliding speed
Why are singletons considered bad?
they are only bad if misused. but they introduce global state to the program. anything can access a singleton at any time and if it has public variables, properties, or methods with side effects then anything can modify its state making debugging harder
Oh okay. Interesting. So they have no influence on performance?
i mean that really depends on your definition of "influence on performance". but in general, no- something being a singleton has no bearing on how it affects performance
Hi ,
how to check if textmeshpro has outline enabled?
How does GetComponent() work? Does it loop over all components starting with the transform, then AIC_Handler, AIC_HealthSystem, etc.?
all i know its small, and inexpensive task, not sure why you care about that ? what are you trying to acomplish ?
Wait, it's inexpensive? Then why is FindObjectWithTag so bad?
I have always tried to avoid GetComponent as much as possible, only doing it once at the start, etc.
the Find methods search the entire hierarchy, GetComponent would only search the object it is called on
but we also don't know how exactly GetComponent is implemented because it is implemented in native code
https://github.com/Unity-Technologies/UnityCsReference/blob/cf0545699c3656babdff41124680a038fbbcef4e/Runtime/Export/Scripting/GameObject.bindings.cs#L37
How does it search the hierarchy? From top to bottom, prioritizing children first?
Wow, okay
this is also unknown
Isn't possible to populate the hierarchy with multiple game objects with the same tag, then seeing which it finds first?
Surely that must make it transparent
https://docs.unity3d.com/2023.2/Documentation/ScriptReference/GameObject.FindWithTag.html
Note: This method returns the first GameObject it finds with the specified tag. If a scene contains multiple active GameObjects with the specified tag, there is no guarantee this method will return a specific GameObject.
That answers that
Probably something to do with what game object is first in memory
How did you mark the text as a quote?
This is cool
> and space before the text
anyone else getting the problem where when you make a gameobject a prefab you cant assign gameobjects and scripts in the inspector? is this a bug or feature?
assets cannot reference scene objects. prefabs are assets so they cannot reference anything in the scene, you would need to pass references when the object is instantiated
this video has a section on how to do so: https://www.youtube.com/watch?v=Ba7ybBDhrY4
thanks
I want to rotate my player around an object. I did this using RotateAround but sith this function it just rotates the player and keeps the velocity to 0. How can i make it so that i can modify the velocity as well?
Maybe someone can answer a question for me. I am learning the Input System, and followed this guide
https://medium.com/@MJQuinn/unity-handling-input-with-the-input-system-2605807fd2c6
I changed some things so the movement would be for my camera and not a player object.
I am reading on docs.unity about the input system and it refers to enabling the action moveAction.Enable()
In the guide that wasn't used and I didn't use it either yet my camera moves around just fine.
Maybe it is because I am using a PlayerInput rather than a InputAction? I have a lot more to read but this has been bothering me.
the PlayerInput component will enable the inputs for you
Ok so maybe PlayerInput does more work for me behind the scene compared to other ones
I have a cube which can be drag and dropped, I'd like to, when it' so over the platform, to kind of lock it in so it hovers and can also be dragged out. I'm considering physics for this, any ideas on what would be a good approach for this?
Any idea what on earth I am doing wrong here? Trying to make a candle script for both lit and unlit candles and turn unlit into lit so they can light other candles. But it only triggers if 2 LitCandles collide.
public class Candle : MonoBehaviour
{
public bool isLit = false;
public GameObject fireEffect; // Reference to the GameObject to be turned on when the candle is lit
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("LitCandle") && !collision.gameObject.GetComponent<Candle>().isLit)
{
Debug.Log("Candle Collide");
collision.gameObject.GetComponent<Candle>().isLit = true;
// Call a function on the other candle's script to trigger the fire effect
collision.gameObject.GetComponent<Candle>().Ignite();
}
}
public void Ignite()
{
isLit = true;
// Turn on the fire effect GameObject if it exists
if (fireEffect != null)
{
fireEffect.SetActive(true);
}
// Change the tag of the candle object to "LitCandle"
gameObject.tag = "LitCandle";
}
}
it won't trigger if the unlit is just tagged "Candle"
you check if the colliding gameobject has the LitCandle tag. then if it does and if its isLit bool is true you then call Ignite on it.
so am I doing it backward? I don't understand
you only check the colliding object then only modify the colliding object
so what happens if the colliding object does not have the LitCandle tag but this object does?
It only works if the colliding object is already LitCandle
I am trying to make it work so the same script can be on both objects
think about it real quick, if this object is a LitCandle but the colliding object is not, which candle will be ignited?
hopefully the unlit candle and get turned into a litcandle
well according to your logic the lit candle will be ignited
so thats why I am asking, where do I have it backward
hi ,
im trying to change TextMeshPro outline color value via code.
i have noticed a strange behaviour and a manual way around it .
public Color _c
textMeshPro.outlineColor = _c;
textMeshPro.ForceMeshUpdate();
the above code alone is not working.... Untile I manually change the color on the editor, it start changing it back to _c 's value.
it seems that i need to do some sort of refresh to the color for it to work, and ForceMeshUpdate(); is not doing it
I am looking at it from the unlit candle side, I have if it collides with a lit candle and is NOT already lit, then run Lit true, and ignite on self.
so you've changed the code to call ignite on this object instead of the colliding object?
ya, the gameobject for lit is itself
show the updated code then
then your answer should have been "no, boxfriend, i have not changed the code so that Ignite is being called on this object, i have left it being called on the colliding object"
ya, I didn't even know that was possible
you didn't know it was possible to call an object's own methods from within that object's methods?
I would have to drag every random flame into the inspector for the gameobject
that's not at all what i said
let me point out your issue again so hopefully you see what is happening:
you check that the colliding object has the LitCandle tag which has been applied by the Ignite method
if it does have that tag (and the second condition is true) you then call the Ignite method on the colliding object (the one with the LitCandle tag)
gotcha, so how do I call ignite on itself instead?
you just call Ignite
is [field:SerializeField] specifically for serializing properties? can't seem to find anything about it
yes, it targets the backing field of an auto-property
nope :S
that target with that specific attribute, yes that is the only use case for it
never seen this before, very interesting
thanks for the link
I think it finally clicked in my head, and it works, thanks dood!
is there a way I can hide/prevent some variables from having default references in the inspector
[HideInInspector] put next to the variable
is it an editor script ?
I believe what you are looking for is making a CustomEditor basically u need to prevent all defaults and serialize only the variables you want to show.
it's a script that other scripts reference but it doesn't live in the scene or have a game object it should be attached to
I was hoping I wouldn't need to write a custom editor specifically for that, it's my first time utilizing default references and I haven't found much or any documentation on how they are intended to be used
I'll try that, ty
Are these fields public or serialized?
they're public and need to be but you saying that made me realize I can just make them {get; private set} and solve my problem
Yes, don't use public fields, use properties
does anyone knows how to fix this ?
the problem is fixed as soon as i opened the color picker and picked any different color
something gets updated and fixes the problem .
I also notice the word ( instance ) appears next to the shader's property bar
it looks as if the game created a new instance of it , that wasnt their before I opened the color picker and changed the color
so far UpdateVertexData(); and ForceMeshUpdate(); does nothing
That means that a new instance of the material is created.
Hello, my On Click () event which is connected to my onEscapeButtonClick() doesn't want to change gameIsPaused boolean to false in my code: https://hatebin.com/kihsfmqqle
I don't think outline color is a property of the mesh. It's most likely a property of the material.
If built-in properties don't work, you could probably set the correct material property via the material reference.
yea, i agree with u , but how could I change it's color ?
Im trying to clone it on run time
Clone what?
Normally setting .outlineColor should work I think. You could try setting the material property directly, as I mentioned before.
im using this for my enemys to shoot, but when i use it for my enemy spawner it starts spawning like 50000 enemies in one second, thing that dont happens with enemy bullets, someone knows what happens? am having this problem since 3 days and no one have been able to help me (i pasted this on general since no one in begginer made to help me out, maybe here someone can help me)
https://pastebin.com/L5Cbhc3v
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.
Perhaps the issue is because yourt cloning something..?@solemn raven
What steps did you take to debug the issue?
wdym?
Hi, I have a question. I'd like to make something like simulacra, but I can't seem to understand the logic behind the coding. Does every app I press on the phone, open a new scene? Is that how it's done? https://www.youtube.com/watch?v=ICQvVQd3gdU&t=2283s&ab_channel=Joshiball
#NoCommentary
โก Want to support the channel? You can do so by:
- Become a Member of the Channel on youtube: https://www.youtube.com/channel/UCxfRp9Kkyr_9oqdMWDLt96g/join
- Sending a Superchat whenever i am Streaming.
โก Social Network Links:
- Twitter: http://twitter.com/Joshiball
- Twitter: http://twitter.com/Joshiballvids ...
So, i have this function that generates a mesh.
the worldHandler.world array is a 2-d array with about 40,000 entries in total inside of it.
Now, this runs kind of smooth as butter.
However, i opened my task manager and noticed that the programs memory usage is rising at a rapid pace.
Do i need to de-allocate something in this script?? I was under the impression that c# kinda does that automatically
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.
From your description it sounds like an issue that would require a thorough debugging. What steps did you take to figure it out?@amber forge
how to clone material the right way ?
Why do you need to clone a material in the first place?
Anyone? ๐
Is onEscapeButtonClick meant to be called when you hit escape, as well as from a Canvas buttons onClick event listeners? Are you hitting escape after pressing the button, changing the states?
This largely looks like multiple Canvas and UI changes to me, im not sure where multiple scenes might be used here
coz that seems to be the only way to change the color, or at least that way we know it's working , I will try clone it , change the color and apply it back to the text meshpro
I don't think that's the issue.
My initial idea was to be able to unpause the game with the esc key, aswell as unpausing the game by clicking the resume button. If I click the esc key the boolean does update, but clicking on the resume button doesn't update the bool.
I tried to assign the color to the material and also didnt work , t seems that i need to update/rerender the material somehow
If you're using the TMP properly as a ui element, you wouldn't need to update anything.
what the editor does is cloning the material appearntly then apply it , i wanna do the same
Iam ...
it just doesnt work
What material does it use?
the default
Ok, that could be the issue.
im talking about the outline tho
Create a new material in the editor and assign it instead of a default one.
Are you sure the function is being called for the button? If you add a Debug.Log, does it print when you click your button?
Yeah, me too.
It does, I'll double check real quick to be sure
Yup it does print the Debug.log
Hey y'all, hopefully Im putting this in the correct place; I was attempting to make a procedural walking script based off a tut on youtube from filmstorm...
While the script seems to work fine, the player movement does not. Unfortunately he did not include that segment in any tutorials I could find, so I had to throw together a root animation blend to try and get something that worked. I got the animations to update correctly (at least I think), but the character fails to move. After some thinking I believe the source is the camera, as he used a third person camera system while I am attempting to use pov. This would be fine but the movement is seemingly based off the position / rotation of the camera and I'm not sure how to adapt the script to match, any Ideas?
https://hastebin.com/share/uyikitobet.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
how do u even assign a material to it ? I think i need to make a new fontAsset
more specifically:
moveTo = forward * inputZ + right * inputX;
with 'forward' and 'right' being camera.forward and camera.right respectivly
Does anything else modify that public gameIsPaused variable in your scene? Also, I assume "MainMenu" is not the same object that has your GamePauseManager script on it?
If you don't want it to be based off the camera, all you need to change is this, no?
var forward = camera.transform.forward;
var right = camera.transform.right;```
make that based off... whatever you actually want it based off.
so pretty much the only thing I need to do is change camera to the position of any object? and If so, would making said object tied to a point in the center of the player view mess anything up?
Wasn't there a field on the component?๐ค
I never said anything about changing the camera. Just change those two lines of code
define forward and right how you want them defined
You said you didn't want it to be based on the camera
what do you want it based on?
sorry I meant change the var camera to any object
Oh sorry I think - yeah I misread
sure if you have some other object that you want to base it off
you can put any Transform you want there basically
all good, I phrased it funky; thanks I'll give it a try!
for example - the player object itself
nope :S and I dont think i need to create an asset font on run time , it has to be some sort of update or a clone and overwriting
or at least that is what seem to be working
The only script that modifies the gameIsPaused variable is the one I sent. The MainMenu is not the same object, but it has a child(The resume button) that has the gamePauseManager script. Also the MainMenu variable would be more appropriately called PauseMenu, my bad.
I would definitely say I'm still a complete beginner, but I have what I think to be a more complex question, so I will ask it here (sorry if this doesnt belong here!) I have a material that I apply to my mesh whenever it satisfies a certain condition, but it is supposed to be merely an overlay. How would I go about "merging" two materials? (as in like, overlapping them). The material I'm overlapping is just a semi-transparent colour tint if that makes things easier, I am trying to make some gameobjects have a red transparent tint to them sometimes and a green transparent tint at other times
What's working? Did you figure it out?
I renamed the MainMenu to PauseMenu, because it makes more sense, but here is how the hierarchy looks.
I dont see anything from what youve shown that looks to be incorrect, if the function is being called, and nothing else modifies the variable, I cant see a reason for it not to change, unless the value starts false, the approach I would normally take for this is using 1 function as a toggle, you may not even need the bool if your "pause menu" active state can act as what your bool would do, you could use a getter property instead if other scripts need to know about the state, for example:
public bool IsPaused {get {return pauseMenu.activeSelf;}}
public void TogglePause(bool isOn)
{
pauseMenu.SetActive(isOn);
Time.timeScale = isOn ? 0 : 1;
}
void Update()
{
if(someKey) {TogglePause(!IsPaused);}
}
Your button then could use the one TogglePause function - this is just personally how I would approach the kind of system your after, maybe easier to manage
unfortunately setting it to another object didn't change anything ๐ฆ
I know its a bit to ask but would you or anyone who reads this be willing to look at the pastebin I linked [in original Q] just to see how the movement script is working (I have an idea but not a full picture). At this point I just want to discern if this is the fault of the script or the root transforms of the animations
I'm trying to make a bit of code that'll clamp the rotation on a GO between 2 values. I thought this'd be straight forward at first as I see that in the Inspector, the rotation values start at 0 and go up past 360 and into the negatives under 0. Unfortunately, when trying to grab the EulerRotation values, it seems to reset above and below 0->360 values instead of giving me the numbers I see in the Inspector.
- Does anyone know how to get the same values as you can see in the inspector?
- Might there be a better way of clamping my rotation values keeping in mind that min/max values might go beyond the bounds of 0->360?
@lament mural assuming the inspector angle is -15, what is the real angle?
The local angle would be 345. Which is what EulerAngle gives me.
Hey guys, I could use a hand with my UI code. I instantiate a bunch of ItemSlot prefabs, and my inventory windows are set with layout group components. Unfortunately because of the instantiation the first time they "open" an inventory in code, the layouts aren't updated and show incorrectly until the next time the windows are disabled -> enabled. I tried using LayoutRebuilder.MarkLayoutForRebuild(windowParent); on a variety of the objects, but it didn't seem to have any affect.
Could always just disable then re-enable the window, no?
Would that not look odd to the player, a window flickering like that before they could interact with it?
right, so switch inspector to debug mode and use that for finding the actual angles
what inspector does is some artist friendly mumbo jumbo, probably uses quaternions to store the user rotation which allows it to display those -720 pop shove it
If it happens in a frame, it'd be fine I think.
nah im being dumb i used -90/90 clamp a lot, its useful
Any idea what that mumbo jumbo might look like because having values that go above and bellow 0->360 would actually be usefull for my clamping to not suddenly jump from one end to another
public static float ClampAngle(float angle, float min, float max)
{
if (angle < -360F)
angle += 360F;
if (angle > 360F)
angle -= 360F;
return Mathf.Clamp(angle, min, max);
}
Tried, doesn't work.
Dirty way I've seen it done is have it in a coroutine that disables, waits a frame, then re-enables. xD
there was a method to force rebuild layout
This would probably be better.
The manual in Auto-Layout refers to LayoutRebuilder.MarkLayoutForRebuild(transform as RectTransform)
try
RectTransform tr;
tr.ForceUpdateRectTransforms();
used on content root?
I've used it on it's parent, it's parent's parent, on the "window" parent...
trying to remember how i did it
Whats frustrating is that it looks right after the window "closes" and "opens" again.
So clearly everything is setup to look properly, but it doesn't update somehow.
It sounds dumb, but I have seen a coroutine that disables, waits a frame, then re-enables work in the past. Keep it as a backup for sanity.
@warm fractal im digging through the sources
CanvasUpdateRegistry.instance
.GetType()
.GetMethod("PerformUpdate", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
.Invoke(CanvasUpdateRegistry.instance, null);
came up with this, testing it myself
you can test as well
Didn't work, but I've got another trick or two up my sleeve to try.
you set the layout dirty before calling it?
any errors?
have to first LayoutRebuilder.MarkLayoutForRebuild(transform as RectTransform)
it adds the hierarchy to a queue, then updates when its procd, directly invoking that method should in theory force an update
hm
I'm actually rather amused by the lack of these working. Does it work for you?
Can someone help, please? I did this to my canvas, but my objects inside the canvas are still showing
Sorry for the late reply, I decided to try following a tutorial and it somehow worked even though the code looks practically the same to what I was writing: https://hatebin.com/hflgpqazol
Also I put the entire PauseMenu Canvas under like a big GameController Empty and I put the PauseMenu Script into the Empty and it works perfectly fine. Here is how the hierarchy for the Canvas looks like now if you're curious. Thank you for helping me out though.
have to create a new project to test, takes time
Didn't mean to come across as rushing, I appreciate the lengths you are going to help though.
dont worry i enjoy this
non programming question
Might it do with the game objects being inactive before/after running the code? Survey says: no.
LayoutRebuilder.MarkLayoutForRebuild(window);
window.ForceUpdateRectTransforms();
CanvasUpdateRegistry.instance
.GetType()
.GetMethod("PerformUpdate", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
.Invoke(CanvasUpdateRegistry.instance, null);```
Like, idk man, I feel like something here would've caused a change, y'know?
the window itself contains the layout?
I'm still testing on each individual GameObject up the hierarchy to test.
So...Yes.
Well I've managed to find out maybe a fraction of a solution
In addition to this code, I'm also running window.gameObject.SetActive(!window.gameObject.activeSelf); twice in a row, and that seems to work for one of the inventory windows. I'm currently experimenting with it, but recompiling every time after a single line of code changed is taking me a bit to figure out.
Oh?
Probably should've mentioned I had it in there too
damn
I had followed this link to the forums about someone using that: https://forum.unity.com/threads/force-immediate-layout-update.372630/
I haven't read the whole forum but since I've come across this haphazard solution I was going to further look into it and experiment. Guess I'll try reading the rest of it tho
canvas is a blackbox btw
I do not know what you mean by "blackbox".
means the c# class is just a wrapper around native one
[FreeFunction("UI::GetETC1SupportedCanvasMaterial")]
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern Material GetETC1SupportedCanvasMaterial();
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern void UpdateCanvasRectTransform(bool alignWithCamera);
example from canvas
so all its internals are hidden in native code
I have never even seen the keywords "internal" or "extern" before
Never had a "formal" training on C# either, ig.
same
Showoff, lol
tho ForceUpdateCanvases() just calls willRenderCanvases event
which is fed delegates you make with MarkLayoutForRebuild(window);
it should work haha why isnt it
missing something
Thats the million dollar question, now isn't it?
Probably to do with my hierarchy, I'm willing to bet.
Time to try a bunch of things with new layouts.
The forum post I linked has a user mentioning it being something about the ContentSizeFitter refreshing before/after the parent does, leading to things not updating properly.
what if you do WaitForEndOfFrame, then call ForceUpdateCanvases multiple times
nah that would clear the "dirty" state on first call
meaning youd have to set the whole thing dirty between calls
assuming the issue is circular dependency like you said
Okay so I have a scene "Abilities" where the player can choose up 4 abilities.
They get added in a List. The game then goes to a "Game" Scene and I want to show the abilities there in a horizontal group layout
https://gdl.space/vodekiwoko.cs
https://cdn.discordapp.com/attachments/497874004401586176/1090474247681490975/image.png
Hi guys,
I'm stuck trying to convert downloaded scores into an integer array. The situation is simple, I'm downloading the following numbers from my table:
20, 7, 2, 23
string RawData = Encoding.UTF8.GetString(www.downloadHandler.data);
I then split them up:
[] Data = RawData.Split(' ');
I then convert them into an integer array:
int[] Score = Array.ConvertAll(Data, int.Parse);
Now normally this works when you manually create an array and populate it with string values and then convert it. however for some reason Unity yells at me and says that my Input string was not in a correct format.
The end goal is simply sort the data from highest to lowest - If there is a better way of doing this, I'm all ears!
Any help would be greatly appreciated!
I want to rotate my player around an object. I did this using RotateAround but sith this function it just rotates the player and keeps the velocity to 0. How can i make it so that i can modify the velocity as well?
Hi guys
Isn't lerp used for arriving at a point over a certain time? How would that help in a calculation?
It's literally just a remapping function that takes 3 values and returns something scaled between the first two
https://unity.huh.how/programming/specifics/lerp/overview
InverseLerp (or unlerp) is the opposite
It doesn't have to be over time. Lerp is just a function that returns value A between values B and C based on T.
The heck is going on with discord here..?๐
Nothing seems wrong on my end, but discord is quite bugged on mobile for me
Ah, that must be the issue.
What am I lerping the rotation and magnitude to?
you can use InverseLerp to get 0-1 value, then Lerp another object using that value as T
what is big O for Mesh.SetVertices, Mesh.SetIndices, and Mesh.SetUVs?
also Mesh.RecalculateBounds, Mesh.RecalculateTangents and Mesh.RecalculateNormals?
and in general, are there publicly available performance tests for Unity api?
First three are probably an O(n) copy
Calculating bounds can definitely be done in O(n)
The Set functions allocate some memory, copy your stuff to that memory then upload it to the GPU when needed
alright thanks
One message removed from a suspended account.
same way you do a constructor for a class:
struct Test
{
float x;
float y;
public Test(float x, float y)
{
this.x = x;
this.y = y;
}
}
One message removed from a suspended account.
How can i manage different game states? Like winner -> stage 2 -> generating new level -> spawning monsters etc...
2 ways that come to mind, you could make a state machine, or a enum and use a index to iterate to the next "state"
private bool spoke = false;
private bool speaking = false;
private IEnumerator PlayDialogue(int dialogueNumber)
{
speaking = true;
DialogueSource.clip = DIALOGUE[dialogueNumber];
DialogueSource.Play();
yield return new WaitForSeconds(DialogueSource.clip.length);
spoke = true;
speaking = false;
}
if (Input.GetKeyDown(KeyCode.E))
{
dialogueNumber++;
NextDialogue.Play();
spoke = false;
StopCoroutine(PlayDialogue(dialogueNumber));
}``` Hey guys StopCoroutine() isnt stopping my PlayDialogue Coroutine, can I have some help please?
Look the example
thanks i already fixed it but will keep this is mind
I have my check game state function: ``` private void CheckGameState()
{
// Check the current game state and update the game accordingly
switch (currentState)
{
case GameState.MainMenu:
// Handle the main menu state
// Go to the main menu scene
break;
case GameState.InGame:
// Handle the in-game state
// Go to the start game scene
break;
case GameState.Paused:
// Handle the paused state
// Show game paused UI
break;
case GameState.GameOver:
// Handle the game over state
// Show game over UI
break;
}
}```
but how do i trigger this with my start button in my mainmenu
Call the function on the button OnClick event from the inspector?
Your function will need to be public for it to be accessible.
What is a controlID for Handles?
How can i make a Character Controller push another one when there is a collision ?
I want my monsters to simply not be stacked in a single pixel but round around the player
i made it public but i doesnt appear.
Hope someone can give me q quick hand with my problem, i got a folder outside my program where i want to load images from, the part which makes this difficult is that the user should be able to put any png image inside that folder and it should work, all solutions i found so far require to give a filename, which isnt an option in my case
How do i properly say this? private void TriggerPause() { // if instate game is ingame if (GameState.InGame) { if (Input.GetKeyDown(KeyCode.Escape)) { GameState.Paused; } } }
Shouldn't you be mentioning currentState in here?
Right now you basically have cs if (5) { 3; }
yes i used this code in gamemanager but switched it over now to gamecontroller
its better
You need to use your variable
but
{
// if instate game is ingame
if (currentState.InGame)
{
if (Input.GetKeyDown(KeyCode.Escape))
{
GameState.Paused;
}
}
}```
i get error
Because... wat???
error CS0176: Member 'GameManager.GameState.InGame' cannot be accessed with an instance reference; qualify it with a type name instead
what was the shortcut in visual studio, to change the name of variables on all places.
right click > refactor > rename
The hotkey shortcut is Ctrl + R x2, going though the context menu with right-click works just as well
You could use System.IO.Directory.GetFiles: https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.getfiles?view=net-8.0 and search for "*.png" as your pattern, that should then give you an array of file paths in that folder whos extension ends with .png, you can then loop through that and do what you need with the file data, if your planning on using this for some kind of "image import" feature, like applying a user texture on something, theres a good chance youll already know the exact image the user wants to use, since they would need some way to "select" that image to be imported anyway
i'll have a look, thanks
not sure which channelt to put this in, Imma just use this one
can unity work with LF file endings?
I finally uploaded my project to git and it said the CRLF fileneding will be replaced by the LF ending, theoratically it has to work just fine, since it is just replacing 0x0D0A with 0x0A, but the qeustion is, if unity supports it
i have like a little problem
Im not sure if just adding a force on collision will solve your problem on its own, it may just make predictable "lines" of your enemies, unless you have very few to begin with - I think what you might be looking for is "AI flocking" or "AI swarming" algorithms, or possibly "object avoidance" using the player and other AI as objects to move close-to but not within the same space the player or others occupy, im not too experienced with implementing those algorithms, though it may be worth looking into, depending on how complex your AI logic is, and how many you may be working with
i have like my gamestate switch in update to check games states, but it also game updating. ``` void Update()
{
CheckGameState();
TriggerPause();
}
public void CheckGameState()
{
// Check the current game state and update the game accordingly
switch (currentState)
{
case GameState.MainMenu:
// Handle the main menu state
// Go to the main menu scene
Do you actually need it to be checked in Update, or do you just need certain systems to know when the state changes to run logic once that change happens? (looking at your comments, a scene load to me, seems like something youd want to do once on an event rather than through Update)
well checkgamestate has to be in update to continuously see which state the game is in.
but i think it triggers so much because i have change scenes yet so it keeps hanging ofcourse
Well how often does your game state change? Wouldnt it only change if something specific happens in the scene? For example, only if the player dies, then the game might change states to a "game over" state, or only if the player hits some end-trigger the game state might change to a "level complete" state? Or are these states something that can change often and not always on something specific happening?
Well what im suggesting is you shouldnt need Update at all, since once a state changes, it likely is going to stay the exact same until some event causes it to change again, so you could setup an event with a property (or function if you prefer) and have things subscribe to thatt event to know when it changes, then keep a static reference of the change, essentially doing the same job as checking in Update every frame, except now its not an "every frame" check just "when x needs to know" check
oke thats new to me
If it helps, heres an example of how I might implement it:
public class SomeGameStateSingleton
{
public static System.Action<GameStateEnum> onStateChanged;
public static GameStateEnum State {get {return currentState;} set {currentState = value; onStateChanged?.Invoke(currentState);}}
static GameStateEnum currentState;
}
public class SomeStateChangeScenario : Mono
{
void OnCollisionEnter(...) {SomeGameStateSingleton.State = changedToState == GameStateEnum.GameOver;}
}
public class SomeSpecificScript : Mono
{
void Start()
{
SomeGameStateSingleton.onStateChanged += DoSomething;
}
void OnDestroy()
{
SomeGameStateSingleton.onStateChanged -= DoSomething; //always unsubscribe at the end of the objects lifespan or use OnEnable/OnDisable instead of Start/Awake and OnDestroy
}
void DoSomething(GameStateEnum changedToState)
{
Debug.Log("state is now: " + changedToState);
if(changedToState == GameStateEnum.GameOver) {...}
}
}
There are other ways you could implement something like this, but this would be the general idea - either a property or a function that lets you change the state, call an event when it changes, subscribe things to the change of the event, if its to a state that thing cares about, perform relevant logic, since the state in this example will stay "GameOver" until something else decides to change it, you dont need Update to check the state, if something needs the current state, it can just check the value of SomeGameStateSingleton.State, or set it to cause a change
Right, and you can keep your enum, in fact this example is under the assumption that your enum logic would be the same as it is now, its just moving checks from having to be done in Update to cover everything, to each thing that actually cares about a specific state to listen for when its relevant, and having game logic (like colliding in a damage zone or enemy killing a player etc), update the state once, which in turn, notifies the code that cares (such as maybe your UI needing to know when the game ends) - in the same example, if the state was say "LoadingLevel", the UI may still be notified, but since the state isnt "GameOver" itll just skip over the code unless you also specifically check for "LoadlingLevel" and "GameOver", if your UI cares about both
I'm trying to add a component using a string, from some reading, it should work using Type.GetType() but I'm having trouble getting this to not return null. Any ideas? Here's my code:
{
string scriptName = e.stateMachineData.states[i].script.name;
Type type = Type.GetType(scriptName);
e.references[i].script = (EnemyState)statesObject.AddComponent(type);
}
I tried even using other types like MeshFilter instead of my custom script and it's still not working :/
I would say you could maybe make a second script and try out the example above, to see if it is what your looking for, it may take a bit to understand it without having an implementation infront of you to see how changing the state affects the things that care about the change - this whole approach is similar to a "messaging" or "observable" pattern if you wanted to find more examples online as well
how do i get the gameobejct that ws dragged in a drag and drop event?
i need to get soem data from a dragegd obejct, but the event of drop is on the slot
how do i do it?
is this all like 1 class?
It's got 2 classes there.... so I'm gonna assume no. Lol
i see like 3
Yeah lol I missed one
Its multiple classes, SomeGameStateSingleton would be similar to what you have, just as a singleton, SomeSpecificScript would be whatever scripts care about a state change or need to perform logic based on a certain state, and SomeStateChangeScenario is whatever causes a state change in your game logic
Why ask if it's all one if you know it's not? ๐
it was a little bit confusing
Tbf, its typed entirely on Discord, so very poor formatting
you could always use hatebin
but basically this code: ```using UnityEngine;
public class GameManager : MonoBehaviour
{
public enum GameState
{
MainMenu,
InGame,
StartGame,
Winner,
NextLevel,
MonsterSpawn,
Paused,
GameOver,
QuitGame
}
}```
i exchange for the first class singleton?
Essentially, yeah, though you can keep your enum as-is, youd just be expanding that class
encountering a litte problem, because in the new scene i dont have the game manager object with the script, and when i do put it in i goes back to mainmenu state.
so how do you track everything across all scenes.
This is what a singleton helps with, although in my example, theres no need to use Update or any Unity specific functions, so it can just be a global class without needing to use MonoBehaviour - if you prefer it to be a part of the scene, youd have to use DontDestroyOnLoad and treat it as a scene-level singleton, ensuring that theres only ever 1 copy of the object/script in the scene at any given time
Anyone? Is there some other way to add a component by string name?
statesObject.AddComponent(scriptName);``` will work.
`string scriptName = e.stateMachineData.states[i].script.name;` < this does NOT seem correct though
what type of variable is script here?
Are you sure you don't want:
Type t = e.stateMachineData.states[i].script.GetType();
statesObject.AddComponent(t);```?
Does GetComponentInParent<T>() allocate garbage? If you have a source for your answer, would appreciate it - ty!
Also it seems like you already know the type of the script will be EnemyState right?
So why not just
statesObject.AddComponent<EnemyState>()
It's one of my enemy state machine states. They are a child class of a state called EnemyState which is a Monobehaviour. Thought maybe since it is a derived class it could cause issue but I tested with some default classes like MeshFilter and SphereCollider with the same issues.
ok so yeah name is not what you want
that gives you the name of the GameObject it's attached to
You should do this
Yes because it is referencing a script asset NOT an instance of a script
which is why I'm using the string
@soft shard trying to implement to second class, but i get error: ``` private GameState currentState;
private GameState changedToState;
void Start()
{
// Set the initial game state
// currentState = GameState.MainMenu;
GameManager.State = changedToState == GameState.MainMenu;
}
error CS0117: 'GameManager' does not contain a definition for 'State'```
wdym by that?
A MonoScript ??
you can't reference script assets at runtime except as a TextAsset
since MonoScript is editor-only
So those are MonoScript fields?
This is a scriptable object that houses all of my state machine states, I want to add each of the state scripts
?
They're UnityEngine.Object fields, maybe that's where I'm wrong
Yes
you can't actually do things this way
the "right way" would be to use https://docs.unity3d.com/ScriptReference/MonoScript.html
but
MonoScript is editor-only
Oh thats my bad, your first comment is correct, its just GameManager.State = GameState.MainMenu; in your case
the actual right way to do this is to use prefabs
This is an editor script
ok if it's an editor script then
MonoScript is the way to go
And it has this:
https://docs.unity3d.com/ScriptReference/MonoScript.GetClass.html
which you can use in AddComponent
Sweet let me try it, thank you. I was having a hard time figuring out how to store a class using an asset rather than an instance. Object was the only thing I could find.
i dont understand one thing, what is the difference between state and currentState, because in the singleton the currentstate is static, what does that mean and will i use it anywhere?
That was the key, was battling this forever, tysm ๐
Well you need to change the static state, but as a property, you cant directly change itself, so the "currentState" acts as the private variable the class uses to change the state, the private variable IS the state, the property just makes it easy/convenient for other things to change that, and fire your event at the same time
but what are we doing here then? GameManager.State = GameState.MainMenu;
arent we directly changing it?
or do i use this private variable? ```public class GameController : MonoBehaviour
{
private GameState currentState;
GameManager or GameController pick one ๐ฌ
Show more of your code hard to say what's going on without seeing it
private GameState currentState;```
delete this variable in GameController
You don't want two variables that mean the same thing
Let GameManager be the source of truth, and the sole place where you store that information
Yes you are directly changing it, thats actually the benifit of having it a property in GameManager, when you set it equal to something different, it fires the onStateChanged event, so if something should change the state, it should just need to call GameManager.State = ... in your case
so in game controller i can now remove checkgamestate function in update
no you still want that
it's just you should be reading the state from game manager directly
i thought the whole implementation of this, is that i dont have to check in update?
the only way around that is if you used a coroutine
which would probably be more complicated
You can keep it, but since GameManager.State fires an event for when it changes, and you can have classes subscribe to that change, I dont think youd need Update - you can still use it if you want for some cases, but I dont think you have to
i will check if it keeps update
Most state machines have:
- on state enter
- update inside the state
- on stat exit
and possibly other things
you will still need update to allow your states to have a per-frame behavior
Oh, is GameState a class all your states will be using, or a enum parts of your game checks for?
enum parts
in game controller in my switch i will write what will happens once the state triggers
Hey, so I have this code that seems like it should work but does not..
- Removing the code in OnCollisionEnter makes it so no object can enter the barrier ever.
- With the code in OnCollisionEnter, the Debug.Logs work properly, it says "Trying to ingore collsion" if the object is allowed, and also allows it, and says "Collision should be blocked" otherwise but it's not colliding (not being blocked by the barrier).
- When the allowed object enters, the BoxController is no longer a trigger and it becomes one again when it leaves (which is the intended behaviour).
- DisableBarrier is not called before the issue happens.
What am I missing? RESOLVED
I'm still dealing with some problem.
as you can see when i click on start button i go to the new scene and in my hierachy everything is empty, how do i transition the state to the new scene
i cant put game controller in there because then everything reloads and it will say, state = gamemenu again.
Just now my Visual Studio Community stopped working with Unity. I think it was when I renamed the folder containing the scripts
A few of the scripts I have open still look fine
The ones that look bad have this "Miscellanuous Files" thing instead of Assembly-CSharp
I'm doing Mathf.CeilToInt(myInt/otherInt) and it's complaining about 'possible loss of fraction.' Isn't that the point, or...?
int/int = int. Do cs (float)myInt/myInt
anytime you do calculation with two ints, it will give an int?
I believe so, yes
weird
Its math?
That looks like the scene is collapsed, and looks like it has loaded correctly, youd have to expand it with the arrow on the left of the scene name to see the hierarchy - though if your using a mono behavior, then you could use Awake and turn your script into a singleton, there are other ways of doing this, but more-or-less similar:
public class SomeClass : Mono
{
public static SomeClass Instance { get; set; }
void Awake()
{
if(Instance != null && Instance != this) {Destroy(gameObject);}
Instance = this;
DontDestroyOnLoad(gameObject);
}
}
SomeClass.Instance is now how that class can be accessed, but I think you could have your state in a non-mono class to begin with and just access it in the same way
You could try restarting VS, if that doesnt work, you should check that VS is set for your external tools, and that its generating the correct assembly files - if you move scripts (or folders of scripts) around that have been previously opened in VS while VS was still open, sometimes VS might not detect an assembly change to reload those scripts, sounds like that maybe is what happened
Thank you. Is this button safe to click?
Regenerating your project files will add all the assemblys checked above (in your case, embedded packages and local packges only), so it may add more .sln files to your root project directory (outside Assets folder), and cause VS to update if its open
So should I click it?
If your assemblies arent loading correctly you can try it, yeah - im just letting you know what it will do
Alright, thanks
so u put this script on a empty gameobject within the new scene?
That script would essentially be your GameManager, if you intend to keep it a mono
You're a lifesaver! Thank you ๐ ๐ ๐
Np
Hey guys, Does anyone know how I can read the processor values in code for the new input system?
so i place gamemanager script on a empty object within my first scene
Whichever scene is your build index 0, yes, though if your testing in other scenes you may need to either load your game from scene 0, or also add that script to the scene your testing in
Does Unity compile to use 32-bit pointers or 64-bit?
๐ฅต thank you for the heavy lifting, haha.
I assume this is where I choose?
I can't find anything about it in the docs
depends on the target
it can do both
yes x86 is 32 bit, x86_64 is 64 bit
Lol, well theres many ways to implement a system like that, this is just one, but sounds like its working out for you
That's what I thought. Great, thanks
So maybe someone can point me in the right direction to tackle this.
Big circle (Parent Object) can Rotate both directions.
Little Circles (Direct Children to Big Circle)
what I want to happen is, the little circles to shoot out the direction of the arrows like the picture(my arrows suck but It just needs the same spacing in a circle around the parent object) regardless of the parent Z rotation.
I suck at angles but curious if there is some nice function that can get me on track to figuring this out.
haven't implemented any game logic yet, just some debug logs and loadscenes to check it out, so we will see.
if the little circles are children they should already be rotating with the parent, so you can just use .localPosition from the parent to move the children
yea i guess my problem is knowing which direction to change the local position
along the vector from the center to the child I imagine
so get the global center position of the parent then transform point of the child local position and draw a line out ?
no, local position
ok i c, to the children, vector 2 zero is center even in local space
in that case if the center of the parent is 0,0 then you could even directly use a scale factor, e.g put child.localPosition += child.localPosition * Time.deltaTime; into update and see what happens
ok lol I feel like an idiot, it literally was just multiplying the current local position. Thanks
How can I call this rcp only on the device the player is on?
[ServerRpc]
public void PlayerSpawnServerRpc()
{
TriviaGameManager.instance.playerCount.Value++;
if (AuthenticationManager.instance.isFbLoggedIn)
{
networkedPlayerNameText.text = AuthenticationManager.instance.playerUserName + $" Player: {TriviaGameManager.instance.playerCount.Value}";
}
else
{
networkedPlayerNameText.text = $"Not Logged In With Fb Player: {TriviaGameManager.instance.playerCount.Value}";
}
}
I call it on 2 devices but the player name only shows twice on the hosting device
I've tried using If ( isLocalPlayer )
if you want to run the function only on local host it shouldn't be an RPC
am I misunderstanding what you mean?
I'd like it to be called on the player as it add +1 to lobby count and sets this players name
like isLocalPlayer.. the player for this machine/device
where is it being invoked from
it's unclear to me:
- what triggers this code
- on which machine it is triggered
- where you want the code to run
- what effect want it to have on which machine
-This code blocked is called in start on player gameobject (when the network spawns the player , this is called on start)
-trigger on any machine/device ( its for my android game)
- I want the code to run when the player is instantiated
-the effect is to have it add 1 to lobby count (and it does) , and set the name for the player
on which machine?
The server?
Some other client?
The client whose player object was just spawned?
All of the above?
Start is going to run on that object on all of those unless you do something to control it
I'll provide a screenshot of whats happening
Each client
Don't crosspost. You were given the answer in the beginner channel (where this question belongs).
I'm lazy I don't want to watch all video...
Give up game development then
It means that there is some memory that hasn't been disposed of by the garbage collector on domain reload. A domain reload typically happens when you enter play mode or recompile code. Did you find a solution to the problem yet?
if I have a component field that isnt visualizable in the editor (a custom object) and I set it using an editor script, does it get stored and serialized?
or do I need to maketi a scriptableObject
if it is a custom class, unity will just ignore it. You would have to handle serialization yourself
Then I am not sure I understood the issue that you are having
I want to know if its possible to do it when the field is hidden
from the inspector
in a gameobject
Ah, I've never done that, but if you are ussing HideInInspector tag it should
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One's at Z -10, not the other
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
Hey! I have a plane mesh and I am trying to figure out how to extrude it. Can someone please help me? this is my mesh and I have tried to use MeshExtrusion.cs but I am getting an error.
Error:
IndexOutOfRangeException: Index was outside the bounds of the array.
MeshExtrusion.ExtrudeMesh (UnityEngine.Mesh srcMesh, UnityEngine.Mesh extrudedMesh, UnityEngine.Matrix4x4[] extrusion, MeshExtrusion+Edge[]
Hi there people, I need help with a script, a smooth camera follow script, I've seen many examples, but all of them are pretty much the same, the camera follows a vehicle
The problem I am having is that this ship moves really fast 800km/h+
And the faster it moves, the farther the camera gets away from the vehicle
I've been struggling to find a way to adjust the smooth time based on the velocity of the ship
This to prevent the camera going too far away at higher velocities
I think you could do something like this
Vector3 lerpedPosition = Vector3.Lerp(transform.position, followTransform.position, lerpSpeed * Time.deltaTime);
Vector3 relativePosition = lerpedPosition - followTransform.position;
transform.position = followTransform.position + Vector3.ClampMagnitude(relativePosition, maxCameraDistance);
Thanks of the advice
I've been struggling with this for days
I think I am going to take a different approach
I am going to parent the camera to the ship and the offset the position and rotation baes on the speed
That way I could do some shaking effect as well
Hello there, this may be a beginner question, but how do I convert from Vector2[] to float2[]? I need to get the UV from a sprite texture but it only returns Vector2[]
Just use a loop and create a new float2 for each element of the Vector2 array . . .
are there any way create asset bundles just include the item you want so i don't have to build the entire scene into the bundle becase i'm getting an erro that not sure how to solve.
here is my client class
using FishNet;
using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace Shiryu.Saikin
{
public class ClientServerManager : MonoBehaviour
{
#if SAIKIN_GAME_SERVER
[SerializeField] private bool autoStartServer = true;
[SerializeField] private bool useSteamworks = false;
#endif
[SerializeField] private int attemptAmount = 1;
[SerializeField] private GameObject retryPanelGO;
[SerializeField] private TextMeshProUGUI retryPanelTMP;
[SerializeField] private Button retryPanelButton;
private void Start()
{
#if SAIKIN_GAME_SERVER
if(autoStartServer) InstanceFinder.ServerManager.StartConnection();
if (useSteamworks)
GetComponentInChildren<SteamManager>(true).gameObject.SetActive(true);
#else
GetComponentInChildren<SteamManager>(true).gameObject.SetActive(true);
#endif
StartCoroutine(StartClient());
}
public void RetryConnect()
{
HideRetryUI();
attemptAmount = 1;
StartCoroutine(StartClient());
ShowConnectingUI();
}
private IEnumerator StartClient()
{
InstanceFinder.ClientManager.StartConnection();
yield return new WaitForSeconds(3);
if (!InstanceFinder.ClientManager.Connection.IsValid)
{
attemptAmount++;
if (attemptAmount < 4)
StartCoroutine(StartClient());
ShowRetryUI();
}
}
private void ShowRetryUI()
{
if (retryPanelTMP) retryPanelTMP.text = "We have attempted to connect to the server 3 times and was unalbe to get a connection. you can click the retry button below to try the connection again.";
if (retryPanelGO) retryPanelGO.SetActive(true);
if (retryPanelButton) retryPanelButton.gameObject.SetActive(true);
}
private void HideRetryUI()
{
if (retryPanelGO) retryPanelGO.SetActive(false);
if (retryPanelButton) retryPanelButton.gameObject.SetActive(false);
if (retryPanelTMP) retryPanelTMP.text = string.Empty;
}
private void ShowConnectingUI()
{
if (retryPanelTMP) retryPanelTMP.text = "Please Wait, Connectiong...";
if (retryPanelGO) retryPanelGO.SetActive(true);
if (retryPanelButton) retryPanelButton.gameObject.SetActive(false);
}
}
}
Can anyone see why my object is not being destroyed when I roll into it? Works fine on other objects
what is MeshExtrusion?
you might get more help in #๐ปโcode-beginner but it's not clear what you mean by "when I roll into it"
you have to set the position of the camera at the right time
Hey guys, I'm having a bit of trouble getting my raycast to follow the game object's rotation. Does anyone know how to solve this? Here's my code
you should be using cinemachine, which deals with all of this
you should be using new Ray(origin: transform.position, direction: transform.forward) as your ray
do you see why that makes sense?
Ah ok, thanks!
i don't remember the api
look at whatever the constructor is for Ray carefully
and use transform.forward as the direction
don't make a node editor
they already exist, many
i have never had an issue with ??
It won't work reliably with anything deriving from UnityEngine.Object
Because it doesn't account for the "destroyed, but not null yet" state of objects, unlike when you use == or !=
is there a json lib in unity or C# that allows me to create json objects dynamically?
like java json.org
so id do something like
JsonObject obj = new JsonObject();
obj.SetInt("intField", 5);
obj.ToString();
ok nvm that doesnt work for me
aagggg
I need a generic Memento object
where I can save ints, strings, AnimationCurves
guess I need to make it
It worked, thanks!
The Newtonsoft JSON for .NET package's JObject class can do this exact thing
what is a Memento object?
Hello everyone.
I have an object that is persistent between levels via. DontDestroyOnLoad. How can I access its contents outside of its original level? Seeing as I just simply drag in the object from the Hierachy.
A memento is a serializable object that stores the state of a non serializable object
ok - why does it need to be "generic"?
(note that JObject from Newtonsoft will indeed do what you originally asked for)
Typically you use the singleton pattern and have a static accessor property for it.
Right, OK. I remember something along those lines but don't remember how to set it up.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
public List<Inventory_BaseClass> inventorySlots;
private static Inventory inventoryInstance;
// Start is called before the first frame update
void Awake()
{
DontDestroyOnLoad(this.gameObject);
if (inventoryInstance == null)
{
inventoryInstance = this;
}
else
{
Object.Destroy(gameObject);
}
}
}
either make inventoryInstance public or add a public property that allows access to it
e.g.
public static Inventory Instance => inventoryInstance;```
that's all
This line would access it from any other script? Or am I misunderstanding here.
Nope, thats just another way to set its access.
this is a public property
you can access this property from anywhere
by typing Inventory.Instance
Because I will have like 30 different objects and I don't feel like creating a memento for each one
Ah, okay, that makes sense.
How does JObject help you here though? Then instead of creating classes you end up just writing the parsing / serializing code for each one
either way you're going to have to write stuff for each one
Yeah
I don't really know if I can create a class tho, because I need to store it in a class without knowing what it is
I think that shouldn't be a problem tho
Idk
I don't get what you mean
I have done this before but not in unity
If you "don't know what it is" wouldn't you have that same problem with JObject too?
what's the use case here?
Ok so you have polymorphism
and you aren't sure how to handle deserializing into subclasses
when you have a List<ParentClass>
something like that?
Newtonsoft JSON actually has a solution for this:
https://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm
Okay, so if I understand correctly. This goes in the global script.
public static Inventory inventoryInstance;
And this goes in the script I want to reference it?
public Inventory = Inventory.Instance;
Doesn't quite seem to work.
How can you break the current Update loop when you aren't on update but on a function ?
return a value from that function to update to tell update to return
no
you don't need this at all, delete it:
public Inventory = Inventory.Instance;
how you do that
just type Inventory.Instance directly whenever you want to use it @arctic marsh
bool MyFunc() {
if (something) return true;
return false;
}
void Update() {
bool shouldStop = MyFunc();
if (shouldStop) return;
}```
so you need to put this after each function ?
you put it anywhere you want to conditionally stop running Update
ok bc i need to stop for a frame when i enable disable nav mesh agent obstacle
Ok, it gives me an error saying it doesn't contain a definition for it.
what says what doesn't contain a definition for what
you have to show me what you tried
Yes, basically
Well
I have the type serialized fine
But the fields are the problem
Hold on I might have been an idiot.
Yep. I was.
Alright, thank you @leaden ice , this makes quite a lot of sense.
I get a nullpointer error for doing this in engine.
public List<Inventory_BaseClass> inventory;
// Start is called before the first frame update
void Start()
{
inventory = Inventory.Instance.inventorySlots;
}
Obviously this is because nothing exists yet, it wont do until the games first loaded.
Can I suppress this error or should I do something else?
You should assign Inventory.Instance in Awake
Awake: initialize yourself
Start: get references from other scripts
why are you doing this
generally the point of the singleton inventory is to have one centralized place to access it
Ok, let me explain my end goal.
I have a pickup system, I add these items to a List in an Inventory object that persists throughout all levels.
This script, I want to get all of that data and add it to a UI display.
the UI display is in a different scene entirely though
^
Right, which is what I thought I was doing, I wasn't ignoring you. Again I'm just trying to access that information now.
Well obviously yes the inventory needs to exist before you access it
Yep.
Which is why it probably throws the error in editor, but would probably work fine in a build.
Can't hurt to try, but I'd need to suppress that error somehow.
Is there a way to do IAP only through code? Everything I find requires an IAP button which I cant use for design reasons
Does the IAP button not just call some method that you could call yourself?
Hmmm, not sure, from what I was seeing it had a few fields you had to drag in
Ill certainly try and look into that
From what I was seeing it took like a function to execute when successful
the object doesn't even seem to recognize that its not meant to destroy itself on load, do variables within these objects get reset also?
Check the source code of that component.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
public List<Inventory_BaseClass> inventorySlots;
public static Inventory inventoryInstance;
public static Inventory Instance => inventoryInstance;
// Start is called before the first frame update
void Awake()
{
DontDestroyOnLoad(this.gameObject);
if (inventoryInstance == null)
{
inventoryInstance = this;
}
else
{
Object.Destroy(gameObject);
}
}
}
To do that would I just try to create a new() in code with its name and go to it from there?
Yea or you could try right clicking the component to see if it has "Edit Script"
Thanks!
@oblique spoke is there a way to create Products for the IAP Catalog through code also?
Hey guys!
I'm experiencing a whack issue;
I have two integers, the static will update, but the local integer stays on 0 even if I increment it. ๐คฃ ๐ญ
Any idea why this might be the case?
Haven't used the package, but I would imagine so.
I am fed-up with the bug of scroll wheel. Since I am using laptop and obviously there is no scroll wheel in laptop and so when I use scroll wheel it in my unity code for zoom it either return 0 or returns the delta moved and moves my camera accordingly
void HandleZoom() {
// Get the distance between the camera and the target object
float distance = Vector3.Distance(transform.position, transform.position);
// Calculate the new field of view based on the distance
float fov = Mathf.Lerp(maxZoom, minZoom, distance / 100.0f);
// Set the camera's field of view
cinemachineCam.m_Lens.FieldOfView= fov;
// Zoom in/out using the mouse scroll wheel
float scroll = Input.GetAxis("Mouse ScrollWheel");
transform.position += transform.forward * scroll * zoomSpeed;
}
currently it has no action on the usual way we use scrolling on touchpad
it is reflecting the change in position of my camera when I move my cursor
float distance = Vector3.Distance(transform.position, transform.position);
that line doesn't seem right
wait umm sorry let me fix it real quick
void HandleZoom() {
// Get the distance between the camera and the target object
float distance = Vector3.Distance(camera.transform.position, transform.position);
// Calculate the new field of view based on the distance
float fov = Mathf.Lerp(maxZoom, minZoom, distance / 100.0f);
// Set the camera's field of view
cinemachineCam.m_Lens.FieldOfView= fov;
// Zoom in/out using the mouse scroll wheel
float scroll = Input.GetAxis("Mouse ScrollWheel");
transform.position += camera.transform.forward * scroll * zoomSpeed;
}
here is the new code but no effect
I am not familiar with getting mouse wheel. Is Input.mouseScrollDelta not fitting your requirements?
let me try it again used it in early stage but it looked buggy or maybe I couldn't figure it out
Hey @spiral ibex thank you. Input.mouseScrollDelta worked perfectly fine. IDK what I did wrong back then.
ยฏ_(ใ)_/ยฏ
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
public List<Inventory_BaseClass> inventorySlots;
public static Inventory inventoryInstance;
public static Inventory Instance => inventoryInstance;
// Start is called before the first frame update
void Awake()
{
if (inventoryInstance == null)
{
inventoryInstance = this;
DontDestroyOnLoad(this.gameObject);
}
else
{
Destroy(gameObject);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DisplayItems : MonoBehaviour
{
public Inventory refInventory;
public List<Inventory_BaseClass> refInventorySlots;
// Start is called before the first frame update
void Awake()
{
refInventory = FindObjectOfType<Inventory>();
refInventorySlots = refInventory.inventorySlots;
}
void Start()
{
}
// Update is called once per frame
void Update()
{
Debug.Log(refInventorySlots.Count);
}
}
Whenever I reopen the scene that initially has the first script, the inventorySlots list is completely cleared, does anyone know why?
I'm making Breakout/Brick Breaker. My bricks change color as they decrease in HitPoints (similar how balloons work in Bloons Tower Defense games). A brick modifies its Sprite Renderer in the set component of the HitPoints property, so when HitPoints is changed, the sprite is automatically updated. A brick's maximum hit points is determined by a serializable field. How can I make a brick automatically change its sprite when its maximum hit points field is updated in the editor? i.e. In edit mode?
HitPoints = HitPoints; in OnValidate()
https://hastebin.skyra.pw/ewexisosin.csharp
I'm getting UnassignedReferenceException: The variable <SpriteRenderer>k__BackingField of Brick has not been assigned. YOu probably need to assign the <SpriteRenderer>k__BackingField variable of the Brick script in the inspector. and NullReferenceException: Object reference not set to an instance of an object - Brick.set_HitPoints at Brick.cs:40
you'll need to assign to the backing field if you're using OnValidate since the SpriteRenderer property is only assigned in Awake which only happens at runtime, but OnValidate happens at edit time
RIGHT! Thank you!
however doing so won't update the sprite which was why you were assigning to the property
Actually, I'm a bit confused...
You'll need to provide more code for context.
if you use an explicit backing field for the sprite renderer that you assign in the inspector (or expose the automatically generated backing field to the inspector) you won't have to worry about that (though you should still null check the sprite renderer before changing its sprite property just in case
Fixed it ๐
none of those codes you sent actually modify the inventory slots list. Do you not have another where that's accomplished?
I cant manage to get serialization to work fine on a scriptable object.
I have an array of custom objects (marked with [Serializable]) that dont seem to get serialized.
I dont know what else to try at this point
you'll need to provide relevant context such as the code
Send the code for the serializable objects and the scriptable object for some context if possible
whoops, sorry :p
The sprite renderer doesn't really need to be a property, I was just messing with things. Could I just make it a public/serialized field and set it in the editor? Is that the same as what you're suggesting?
I do, its a long script though. Let me go upload it somewhere.
yes
Oh and just a wild guess, but try changing refInventory = FindObjectOfType<Inventory>(); to refInventory = Inventory.Instance;
I tried both methods, but I will do so again.
all you need to do is make sure that the SpriteRenderer is assigned before assigning to the HitPoints property (and maybe throw a null check into the property setter just in case)
PlantDefinition: https://hastebin.com/share/gakonozedo.csharp
NodeData: https://hastebin.com/share/orotucetab.csharp
NodeMemento: https://hastebin.com/share/oxemetujuy.csharp
NodeConnectionData: https://hastebin.com/share/ojopabiceh.csharp
The class im serializing is PlantDefinition (the scriptableObject) The rest of the classes are referenced there
what IDE I should not use? seems like there are issues with vscode?
vscode is fine, rider is awesome
You should use VS
okay, just had some issues with vsc, reinstalling it to see if that helps.
all of the fields in your NodeData and NodeConnectionData classes are readonly. unity cannot serialize readonly fields
oh... why?
https://srcshare.io/6424bc1ecd2a28af1228b965
https://srcshare.io/6424bc5ccd2a28af1228b969
https://srcshare.io/6424bc70cd2a28af1228b96d
Here are all three scripts in question.
because they can only be set via ctor or field initializer. unity's serialization happens after those
theres been a few updates here and there, those are the most up-to-date.
yeah it's what I'm sort of used to, but I'm getting the .net errors. can't remember how I fixed them the last time.
ok makes sense
VSC is unsupported officially (debugging no longer works) and should be avoided unless you're a Linux user without the premium rider - you've got little choice if so.
in java you can serialize final fields with reflection magic
thought it would be the same in C#
i'll create getters
and make them private I guess
can it serialize private fields?
Are you sure there aren't any more instances?
VS shouldn't have many issues. VSC will require third party extensions and even then, I would not be certain you'd be issue free.
I am fairly certain, yes.
Ok, I'll pass on vsc then. I'll try VS but even there I had issues with code completion
Wait, when you changed the line I mentioned, did it break your game?
Make sure you follow the manual installation guide as the via Unity Hub version skips the step of setting up the workloads.
No, this has been a persistent issue. However I'm about to try something, the InventorySlots variable isn't static, so its getting reset every load I assume.
If using Hub to install, just ignore the download step in manual and do the rest.
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
it's not usually worth the hassle of doing that but it is possible.
and yes private fields can be serialized with unity's serialization using the SerializeField attribute
https://hastebin.skyra.pw/xixuhuyaqo.csharp
Now i get UnassignedReferenceException: The variable spriteRenderer of Brick has not been assigned. for each Brick in my scene...
that finally worked, thanks a lot
got it, it's installing now
is there a way I can set up unity events (or any other way to call simple methods) with scriptable objects?
An example of intended behavior would be having an empty game object with the unity event on it (because then it can reference the methods I need), but it would be easier for my designers if it was a scriptable object because the methods it calls are identical across scenes
I thought I could just put unity events as a variable in a scriptable object and call it a day, but it can't actually reference any methods in my scene
ScriptableObjects exist within your project. Referencing scene objects is not what they're made for.
I understand that part, but the methods I need to reference are static. I know unity events probably won't work for this, I'm looking for suggestions for similar functionality (where I can expose which methods get called in a designer-friendly way)
effectively, what has been requested is a stack of methods where the order can be changed easily. I figured scriptable objects were a good way to structure it, but I'd like to not need to hide it all behind an enum with a hardcoded reference to each method (which is the only other idea I have right now)
I never tried it, can you create methods within your scriptableobject that executes these static methods, then link the object itself and select them?
nope, I tried that as well
What didn't work with the above suggestion?
Certainly it'd be able to reference those methods from itself
@dusk apex I guess code completion doesn't work by the looks of it?
Assuming it's configured via workload, you'd then need to set it up as the external script editor. https://learn.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity?pivots=windows#configure-unity-to-use-visual-studio
yeah it's weird because I have it set up like this
Did you complete all of the steps?
I believe so, let me restart Unity
I guess I should say a unity event can't select the method on itself. Is there a different way I should be referencing itself (aside from wrapping it enums, as I mentioned)
The Animator Controller (TileAnimController) you have used is not valid. Animations will not play what this mean and how do i fix
yeah I just went over the list again and I've done everything.
Can you show the external tools? It should look something like this..
Also, try restarting VS
fixed. reloaded the assembly and it seems to be working fine now
thank you
bump - I'm trying to change my Brick's sprite when its HitPoints value is updated, and change the sprite automatically when maxHitPoints is changed in the Editor
Are there spriterenderers at the gameobjects this brick component is attached at?
Yes, my Brick prefab (which does not have any instances where the sprite renderer is overridden) has a sprite renderer. I even added [RequireComponent(typeof(SpriteRenderer))] to the class.
how do i play an animation
animator.Play()
Ok, haven't been able to solve my issue. Apparently if its not a static variable it gets reset, but I cant modify the defaults of a static list, either.
It should be able to...
[CreateAssetMenu(fileName = "ExampleSO", menuName = "ScriptableObjects/ExampleSO", order = 1)]
public class ExampleSO : ScriptableObject
{
public UnityEvent exampleEvents;
public void Print(string str) => Debug.Log($"{name}: {str}");
}```
Can you try changing the debug log in your update method to not using a cached reference. Aka do Debug.Log(Inventory.items.count)(i don't remember your member names, sorry ๐ )
for animator.Play(string) the input is just the name of the state you want to play.
Sure, give me a min while I try to fix this other issu
The Animator Controller (TileAC) you have used is not valid. Animations will not play
why does it keep saying this
unity after making their animation system unnecessarily complicated:
Is it guaranteed Awake or OnEnable of a scriptableobject is called in runtime (after building on device)?
That scriptable object has bee assigned into a mono script in a scene. I mean it has not been created at runtime.
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
They just talk about it in editor time.
nope
read it again
they talk about runtime as well.
You obviously need to assign the field in the editor. And don't forget about that null check I keep suggesting
I want to get a data from disk at the beginning in a scriptable object and then use it.
I decided to get data in editor time and then serialize it
Can you not lazy load it?
public Data myData;
public Data MyData{
get{
if(myData == null){
//load from disk
}
return myData;
}
}
something like this
Creating a new scriptable object in the project, during editor time:
Only the created scriptable object
- Awake()
- OnEnable()
Script reload:
All Scriptable objects in the project
- OnDisable()
- OnEnable()
Scriptable object instantiated at runtime:
Only the instantiated scriptable object
- Awake()
- OnEnable()
Scriptable object instance destroyed at runtime:
Only the destroyed scriptable object instance
- OnDisable()
- OnDestroy()
Editor startup:
All Scriptable objects in the project
- Awake()
- OnEnable()
Destroying an object in the project, during editor time:
0. No callbacks are called
I see only Scriptable object instantiated at runtime:
I do not instantiate it in runtime by ScriptableObject.CreateInstance()
Alright.
Where is the Visual Scripting section?
Scriptable object instantiated at runtime:
Only the instantiated scriptable object
1. Awake()
2. OnEnable()```
this part
Thx
Is OnDisable not called the first time a GameObject gets SetActive(false)?
Scenario...
- Scene starts with GameObject in question inactive.
- Through player input the GameObject gets SetActive(true).
- Through player input the GameObject gets SetActive(false). ...but OnDisable does not trigger.
- Through player input the GameObject gets SetActive(true) again...
- Through player input the GameObject gets SetActive(false) again...and THIS time OnDisable triggers.
how do i get a child of a gameobject
No, it should be called
It is called every time the game object is disabled.
Here's some code I use for testing.
using UnityEngine;
public class MonoExecutionOrder : MonoBehaviour
{
private void Awake() { Debug.Log(gameObject.name + "\tAwake\t\t" + Time.time.ToString("F7")); }
private void OnEnable() { Debug.Log(gameObject.name + "\tOnEnable\t\t" + Time.time.ToString("F7")); }
private void Reset() { Debug.Log(gameObject.name + "\tReset\t\t" + Time.time.ToString("F7")); }
private void Start() { Debug.Log(gameObject.name + "\tStart\t\t" + Time.time.ToString("F7")); }
private void FixedUpdate() { Debug.Log(gameObject.name + "\tFixedUpdate\t\t" + Time.time.ToString("F7")); }
private void Update() { Debug.Log(gameObject.name + "\tUpdate\t\t" + Time.time.ToString("F7")); }
private void LateUpdate() { Debug.Log(gameObject.name + "\tLateUpdate\t\t" + Time.time.ToString("F7")); }
private void OnDisable() { Debug.Log(gameObject.name + "\tOnDisable\t\t" + Time.time.ToString("F7")); }
private void OnDestroy() { Debug.Log(gameObject.name + "\tOnDestroy\t\t" + Time.time.ToString("F7")); }
}
Weird...
If you believe code is not acting properly, Restarting Unity can help.
If you have a full script to share --> https://gdl.space
The null check is on line 40 and the spriteRenderer cannot be assigned since it's private. I've got it working now with _spriteRenderer = GetComponent<SpriteRenderer>() inside OnValidate.
Serialize the field like I suggested earlier then just drag the reference in, no need to GetComponent in OnValidate
Ah! I figured it out. I forgot OnEnable is called before Start, and I was re-declaring a List in Start after it was already declared in OnEnable, thus clearing the List. So OnDisable was thinking the List was empty the first time it was called.
The script example above has all the functions in their order of execution.
Happy coding!
Yep! That's what made me realize it. ๐
Can you drag in a component? I thought you can only do it on GameObjects...
Yes
Hey guys, couple questions:
- Whenever you're using scenemanager to additively load scenes, do all of the scenes need to be present in build settings?
and - If I additively load a scene, say Scene B into Scene A, is there any way I can access the contents of scene B from scene A via a script?
- Yes
- It looks like most people are using a static reference
There is a heavy method you can use here if needed though:
https://answers.unity.com/questions/1826841/find-gameobject-in-another-loaded-scene.html
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
FindObjectsOfType should work for all loaded and active scenes though
More examples: https://gamedev.stackexchange.com/questions/126232/get-all-objects-of-additively-loaded-scene-loadscenemode-additive
Gotcha, so I'm trying to load in levels as players get near them, is putting the levels in seperate scenes the way then? Or is it better to store them as prefabs instead
It depends on the nature of your "levels"
and the overall flow of your game
It's an open world kind of deal, but locations need to be loaded in as players get close. The caveat is that the main scene cannot be unloaded as it has like skybox elements
It can be done either way
if you use prefabs you'd want to be using Addressables though
One thing though is that in Unity - scenes are the unit of thing that baked global illumination and baked occlusion culling are associated with
so if those things are important in your game, scenes are probably the way to go
Gotcha, thanks!
Hey, sorry, I know this is probably kind of a dumb question, but what's the utility for using addressables over just plain prefabs? In this use case or in general really. I read the documentation and don't really understand their use case
Hello there, Im following a tutorial on doing mesh generation like minecraft; the code works fine but I would like to add caves, I know I would need to use 3D perlin noise, but my question here is how do I modify my conditional so that I can use 3D noise? like what do I compare the current height with?
Directly referenced prefabs are always loaded in memory.
Addressables lets you keep it unloaded until actually needed
quick question im getting the error that Time does not contain a definition for delta time and am wondering why that would be heres the code
Configure your IDE so it actually functions properly
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
IDE?
damn I was adding the script not the actual scriptable object. That works perfectly, ty for taking the time to record an example
use deltaTime not deltatime
Thanks
and also take a look at what vertx said
_uiCanvas = Instantiate(_uiCanvasObject, Vector2.zero, Quaternion.identity); //initializing UI at runtime
_winCanvas = Instantiate(_winCanvasObject, Vector2.zero, Quaternion.identity);
_pauseCanvas = Instantiate(_pauseCanvasObject, Vector2.zero, Quaternion.identity);
_uiCanvas.SetActive(false);
_winCanvas.SetActive(false);
_pauseCanvas.SetActive(false);
is there any way to shorten these calls?
not really
if you need to assign the game object then set some state for it, those are two separate operations
best you can do is make an game object extension that adds a boolean at the end of the function call to indicate the gameobjects activeness
I am trying to make a shotgun script, it basically does a loop for how many "pellets" I want to shoot, then use a projectile script I use to add the actual speed, I also added a bit of random spread to make it more shotgunny
and even though I am adding different randomness to each pellet they still go in the same direction
code that spawns the pellets and adds random direction: cs for (int i = 0; i < pelletCount; i++) { Projectile p = Instantiate(pellet, shootPoint.position , Quaternion.identity); var newDirection = direction.normalized + spread * (Random.value - 0.5f) * 2; p.Shoot(newDirection); }
code that shoots the projectile:
public void Shoot(Vector3 direction, bool addTourqe = false, bool addUpwards = false)
{
if (addUpwards) direction += Vector3.up * speed / 10f;
if (addTourqe) rigidbody.AddTorque(Vector3.right * speed, ForceMode.Impulse);
transform.forward = direction;
rigidbody.velocity = speed * transform.forward;
}```
I've endlessly debugged, and even implemented different ways of adding the spread like through spinning the projectile in a random direction then shooting it
and I even made sure that randomDirection always does return different values for each iterations
I feel like I'm missing something super obvious
Should I preload the gameplay element from the main menu? Like UI, Photon, Camera, Character,... ? Since those element will always be in gameplay and I can keep data like player equipment from the main menu into gameplay
how many scenes do you have
It's like levels
So each levels will have a different scene
And thereโs about hundreds of them
After each levels player goes back to the level select to goes on to the next level
how is it still giving me this error
context: script belongs to a distractor object, which purpose is to track the closest enemy to it and call the distract() function in the enemy script
if (closestEnemyAI != null && gameObject)
{
enemyAiScript.distract(gameObject);
}
Error:
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
EnemyAI_Script.distract (UnityEngine.GameObject distractor) (at Assets/Scripts/EnemyScripts/EnemyAI_Script.cs:324)
Distractor_Script.startDistractor () (at Assets/Scripts/UncategorizedScripts/Distractor_Script.cs:53)
Distractor_Script.Start () (at Assets/Scripts/UncategorizedScripts/Distractor_Script.cs:66)
here's the screenshot
Hey! Sorry for the last answer, it is from here: https://github.com/nickhall/Unity-Procedural/blob/master/Splines/Assets/Plugins/MeshExtrusion.cs people discused it on the forum here: https://forum.unity.com/threads/how-do-i-extrude-mesh-with-the-meshextrusion-cs-with-another-c-script.428149/ and https://forum.unity.com/threads/how-do-i-extrude-mesh-with-the-meshextrusion-cs-with-another-c-script.427867/ but I did not really understand how to use it.
Spline based mesh generation. Contribute to nickhall/Unity-Procedural development by creating an account on GitHub.
Hello i have been having some trouble trying to Extrude Mesh with the MeshExtrusion.cs(From Unity Procedural Examples Asset) with another C# script, i...
context (mesh extrusion on a 2d plane)
im asked to create a quest system where quest is unlocked based on real life time, server based
just like when player finished the part 1 of the quest, part 2 will be unlocked after certain timer, maybe its 1hr , 1 day or 2 days
my idea is to record the date/time on the moment that user finished the quest, and then unlock the quest after the set timer
but where should i do the validation? i cant do it on update to constantly grab and compare info from server , and how to calculate the time
If you sent the info about the unlock time to the client, then the client could calculate it himself and request the quest reveal when the time is right. That way server would need to validate it only during the player's request.
Alternatively, you could create some sort of sorted structure where all quests would be sorted by their reveal time: that way you would only need to check the first quests in the list and ignore all the quests after the first one that doesn't match the time conditions. It would greatly reduce the number of checks if there are plenty of quests waiting.
i think i will go for first one
i just had a discussion with my team, they decided to go on the first one
Hello, how can I move a sprite in a circle without rotating it?
thx๐
Just... update its position but not its rotation?
ok... but how
here's where a little search could comes in really handy
https://answers.unity.com/questions/1164022/move-a-2d-item-in-a-circle-around-a-fixed-point.html
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
the link without the sass would be appreciated
new Vector2(Mathf.sin(radians), Mathf.cos(radians)) * radius; gives you a point on a circle using an angle
You should know, what features you added, how should we know. Maybe show your script, so we know what you talk about. Does your inventory system block inputs maybe, did you disable scripts for testing and forgot to reenable?
We are in a code channel, so show your code...
yeah, otherwise you just get lose suggestions here cause noone knows, what you did and it could be everything...
Rigidbody removed, velocity set in update, set to kinematic, game paused with timescale, added huge mass, commented out the script part, blocking inputs with another action so you dont fire your script... etc etc etc
Hello! I need some advice about to move a rigidbody properly on slopes. I move my rigidbody modifying velocity vector. The problem is very basic: on steep slopes character speed drops. I am looking for some tutorial to handle this. I already have some raycasting to check if rigidbody is grounded and I think I could do some calculation on ground normal or something like that, but I can't figure it out. Some advice?
SpawnTimeMin : 5
SpawnTimeMax : 8
DistMin : 15
DistMax : 35
Anyone know how I can have one Variable (ManageCreep) who's min value is 0 and max value is 1 to handle both SpawnTime and Dist min and max together?
if you get a hit point, you can use its vector to determine the slope angle and add that as a force direction
you mean like a get set? that clamps to your values?
raycast downward, get the normal of the slope, then you can use Vector3.ProjectOnPlane
like when I have ManagerCreep at 0
SpawnTime will be at 5
Dist will be at 15
ManagerCreep at 0.5
SpawnTime will be at 6.5
Dist will be at 25
ManagerCreep at 1
SpawnTime will be at 8
Dist will be at 35
but I only want to change ManagerCreep that in turns changes the other two accordingly
Then you would use getters and setters to update those values based on another one
trying to find examples but I dont get it
[SerializeField]
public int strength
{
get {return m_strength; }
set {m_strength = value; }
}
public int m_strength;
This is how you can get and set values. from there you can go and do whatever you need to change on your variables
And through what would you switch? All floast that are possible from 0.000 to 1.000 ?
He wants to set two OTHER values to a specific mathematical relation to a MAIN VALUE, so he could just use get to get the main value + his calculation
Dont overcomplicate things here. Or he could also just use a public void to set them if he wants to rely on methods
Ok I got it! thanks guys ๐
Nope, if they are in the inspector, those will be the default values for the build
Unless you change them by code ๐
No no, inspector values will always be exported as default values. Even if you lets say first write public float myFloat = 20, then change it inspector, the inspector value will override the 20 in your code when initialised.
Hi, I am trying to set the timer for 1hr but the script is not working beyond 90000 ms(miliseconds). Here is the script Link:https://hastebin.com/share/vakemidufa.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I suggest look into this post: https://answers.unity.com/questions/1193407/make-a-countdown-timer.html
Especially how to compare datetimes and use the ToString() method to print out your desired values without weird calculations ๐
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
And to get the target value in one hour, you can just use https://learn.microsoft.com/en-us/dotnet/api/system.datetime.addhours?view=net-7.0
https://blog.unity.com/engine-platform/advanced-editor-scripting-hacks-to-save-you-time-part-1
Is there any source for the example showed in this guide ?
Hello, I've created this static class and I'm trying to call the SendJson function from another script but it's not getting called
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public static class JsonSender
{
public static void SendJson(string json)
{
MonoBehaviour reference = new MonoBehaviour();
reference.StartCoroutine(SendRequest(ApiUrls.PostDataUrl, json));
Debug.Log($"World");
}
}
public class ProceedToSendJson : MonoBehaviour
{
public void ClickToSendJson()
{
Debug.Log($"hello");
string json = UserDataManager.instance.ToJson();
JsonSender.SendJson(json);
}
}
I get "hello" but not "World"
Right click JsonSender.SendJson in ClickToSendJson and click "Go to definition". Does it go to the right method?
yes
Can you place a log before MonoBehaviour reference = new MonoBehaviour(); and test if that logs?
ok wait
Considering your method content is invalid, it might be blocking
You cannot new a Monobehavior
So this is a fundamental problem with your setup
Just pass the caller to the function and use that to start the coroutine
yes logging world now showing now
so i just remove Monobehivour right?
I mean should i remove MonoBehaviour reference = new MonoBehaviour();
okay
ok so the entire script looks like the following, now SendJson is getting called but not the SendRequest() which either logs "error" or "success" message
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public static class JsonSender
{
public static void SendJson(string json)
{
Debug.Log($"world");
// MonoBehaviour reference = new MonoBehaviour();
SendRequest(ApiUrls.PostDataUrl, json);
}
private static IEnumerator SendRequest(string url, string json)
{
// Create a new UnityWebRequest object
var request = new UnityWebRequest(url, "POST");
// Set the request's content type to "application/json"
request.SetRequestHeader("Content-Type", "application/json");
// Convert the JSON string to a byte array
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(json);
// Set the request's upload handler to upload the byte array
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
// Set the request's download handler to download data to a byte array
request.downloadHandler = new DownloadHandlerBuffer();
// Send the request and wait for a response
yield return request.SendWebRequest();
// Check if there was an error with the request
if (request.result != UnityWebRequest.Result.Success)
{
Debug.Log("Error sending request: " + request.error);
}
else
{
Debug.Log("Request sent successfully!");
}
// Dispose of the UnityWebRequest object
request.Dispose();
}
}
ok, so as suggested you need to pass a MonoBehaviour parameter to SendJson so you can use that to Start SendRequest as a Coroutine
like how I did here?
yes, except the MonoBehaviour reference needs to be a parameter not declared in the method
can you tell me how? I did not understood.
public static void SendJson(string json, MonoBehaviour reference)
then to call it
JsonSender.SendJson(json, this);
ok let me try
btw SendJson is my custom made function and not some package. So will it work?
yes
Am I doing gitignore correctly?
# Type cache
/[Aa]ssets/[Rr]esources/[Mm]VVMToolkit.meta
/[Aa]ssets/[Rr]esources/[Mm]VVMToolkit/*
for some reason it doesn't work
any help, getting this error: Assets\TsTubeMove.cs(26,18): error CS1061: 'GameObject' does not contain a definition for 'tranform' and no accessible extension method 'tranform' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)
Please properly configure your !ide in order to fix your issue
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
what?
Your editor is not configured. Configuring will solve your problem.
Remove the first /
how do i configure it
You follow the link that works for you (I'm guessing Visual Studio, manually), and you configure it.
all default have it
okay thanks
This won't work because an IEnumerator yields and pauses. This is c# behaviour and if you call it manually, the code will stop at yield return request.SendWebRequest();. StartCoroutine fixes this by making Unity handle the yield operations based on what must be yielded. You can't properly handle a Coroutine unless you manually implement a handler for it, which is way too complicated and unneeded.
What you could be doing is making your method asynchronous. Then you can send your method and asynchronously wait for a result.
Problem is, this is complicated.
Another solution is making this JsonSender a singleton, and have it inherit from a MonoBehaviour:
-- public static class JsonSender
++ public class JsonSender: MonoBehaviour
{
++ public static JsonSender Instance { get; private set; }
++ private void Awake()
++ {
++ Instance = this;
++ }
public static void SendJson(string json)
{
-- MonoBehaviour reference = new MonoBehaviour();
-- reference.StartCoroutine(SendRequest(ApiUrls.PostDataUrl, json));
++ StartCoroutine(SendRequest(ApiUrls.PostDataUrl, json));
Debug.Log($"World");
}
}
public class ProceedToSendJson : MonoBehaviour
{
public void ClickToSendJson()
{
Debug.Log($"hello");
string json = UserDataManager.instance.ToJson();
-- JsonSender.SendJson(json);
++ JsonSender.Instance.SendJson(json);
}
}
Notice how you can use StartCoroutine like normal now.
You just need to add it to a component, and it will work.
Ok my bad. Have the files you're trying to ignore already been committed?
I did this but but SendRequest is not getting Called I guess, I added 2 log message above and below reference.StartCoroutine(SendRequest(ApiUrls.PostDataUrl, json)); , both of them are getting logged, but nothing inside SendRequest is getting logged.
no
do they show up in git status?
That's because of the yield instruction like I explained in my previous message. I gave a solution: https://discordapp.com/channels/489222168727519232/763495187787677697/1090959882204749845
not familiar with that view. type "git status" into your terminal in the git repo
Ohh ok ok, I'll try this
ok so as you said the SendRequest() will stop at yield, so if I add a log message at the top of the function will it log?
I added highlighting to the code I changed
Yep No, not in these methods
My mistake, you specifically need to call Current on it to get the value
var enumerator = SendRequest(ApiUrls.PostDataUrl, json);
var first = enumerator.Current;
enumerator.MoveNext();
var second = enumerator.Current;
Something like this
ohk ohk
Unity does this internally when you use StartCoroutine
if you look at this code, to send a json payload to any given URL, do you think this is correct(with the changes you suggested), or is there any other way I can achieve this?
If it works, it's fine
I would argue you make it asynchronous and upload using a HttpClient instead of the build in Unity solution but that's just more complex
got it
If on my Update i run a coroutine with yield for a frame does that pause my update loop or not ?