#archived-code-general
1 messages · Page 13 of 1
yeah that error might have stopped it somehow. Always fix/catch errors
Just did some further testing, and weirdly it only destroys half the time when colliding. Thats a bug i shall now fix
yeah, just any piece in the new section would do, as you'll end up needing to do some kind of bfs/graph search to find all connected pieces to it, and that will find any/all of them
breadth-first search
you may want to look into other graph algorithms as well as there's a lot of very helpful and powerful things 👍
how could i have a proper drop-down menu, not that thing where you click the dot, and detect which option is selected out of the drop-down
if (CanMove(speed))
{
_animator.SetFloat(SPEED, _id == 1 ? -speed : speed);
Debug.Log(_id);
}
else
_animator.SetFloat(SPEED, 0);
This function returns values between 1 and -1 but if I add the player controller script and a second player using input system the function only returns values between -1 and 0 never +1. It works as expected if the player controller script is not used.
Here is the full code:
Movement controller: https://hatebin.com/isrhtubukh
Player Controller: https://hatebin.com/scfmvqmgyb
then i’m sure it’s something with your player controller. Are they talking to each other?
so when you add the player controller it seems like it’s never reading the speed as positive
least that’s what i’m interpreting
probably not though i don’t see how that could be
imgUI[i].sprite = Sprite.Create(filtered[i].normal, imgUI[i].rectTransform.rect, imgUI[i].transform.position);
Im trying to give my uimage one of my default textures types… this has no errors but isn’t working either
Help
@swift falcon you might get better luck here #🧰┃ui-toolkit
Hey guys, so I've got an orthographic camera with a zoom that is managed by altering the orthographic size, but I'm facing a problem with Audio Sources. Essentially, I need to adjust the volume of world placed Audio Sources depending on how zoomed in the camera is. At the moment, the volume doesn't change since it's just effecting the size of the camera instead of the position. Anyone advice would be much appreciated 👍
Then change it based on size?
hey guys
why is tghis giving me null refrence? line 100
the stages.length is 4 as it shuld be
There’s quite a few different audio sources in different positions across the world so manually adjusting isn’t really ideal
I didn't infer to manually adjusting it
Take the variable that changes and base your volume on that
Which you seem to imply size in this case
I might be understanding your issue wrong though
You print out the same stuff here.
thats irelavent to the issue
You make the stages array the length of the keys
doesnt that make instances or something
Afaik, you currently have an array that can have Stage objects in it, it currently has 4 places in that array, and they are all null.
Just set a breakpoint there. And check what's in the array.
ok
Would I be able to do that since it’s in a 3d space though? The size of the camera doesn’t necessarily mean it’s closer to said object in my case as they’re all in different position.
Do you want it based on position or size?
Does the position remain the same for the camera during the entire scene? But each have their own position?
Same goes for the size?
https://docs.unity3d.com/ScriptReference/AudioListener.html
Just Lerp the .volume depending on the zoom level?
(if the cameras remain on the same position for the entire scene, you only have to run it once in start, for each seperate camera)
The camera is controlled by the player so it changes, but they also can zoom the camera in and out (affecting the size). As is the audio sources are based on position. I need to basically simulate the size/zoom as getting physically closer to the audio sources.
Okay thanks guys, I’ll give it a try and see if it fixes my problem 👍
guys im having problem
unity error log told me that the UpdateValue is the problem
show the error
Also cache the getcomponent
uhhh i miss pressed enter
its too soon
im opening unity xd
Where can I ask questions related to license?
its look like it cant get this component
ohhh i see
are you going to show the error or not
because i put the call before set parent so it cant get component in parent
it say wpnBase is null
show the error in the console
alright that might be long
avg open project time is about 25m xd
but i fixed it bro
oh nvm
anyone knows how to combine some sprites with their positions and sizes to a one sprite?
anyone know how i could get a proper drop-down box in the inspector and check which option is selected?
You can use Enums
Else you'll have to use #↕️┃editor-extensions
Afaik Enums are the only thing that create a dropdown in Unity's Inspector
could you show me how to do that?
Google can
It's quite simple though
public Enum MyEnum
{
One,
Two,
Three
}
[SerializeField] private MyEnum myEnum;
@devout solstice
Alright
And how do i check which is selected? And most importantly how do i assign what each selection does
i tried to look it up but couldn’t figure it out
{
One = 1,
Two = 2,
Three = 3
}
[SerializeField] private MyEnum myEnum;
private void Update()
{
switch(((int)myEnum)
{
case 1:
Debug.Log(1);
// code block
break;
case 2:
Debug.Log(2);
// code block
break;
case 3:
Debug.Log();
// code block
break;
default:
break;
}
it will be longer if use string xd
Oh and that’ll return a bool?
yes
ok
you can look at enum vids and blogs in beginner c# tutorials . . .
no need to cast to int, just use the enum as the case MyEnum.One: . . .
i usually use it while using 2 enum
#💻┃code-beginner error explains the problem and fix . . .
you need to check if the value is null, it will return null if nothing is found . . .
hmmm it found
and assigned but very freaking weird
Hey guys, can't seem to find informations about Unity's grid system. I have to use if for an educational but can't find any ressources on using it in a 3D space, can someone help me do that? The goal is making a sokoban 3D where I need a grid to know wether there's a wall or the player for example in a cell at any given moment
what issues are you having with it?
Information is here: https://docs.unity3d.com/Manual/class-Grid.html
https://docs.unity3d.com/ScriptReference/Grid.html
I just can't seem to understand how to initialize it in a 3D space and how to manage it
I can't use rigidbodies or colliders in the project
make sure you don't have any duplicate scripts in the scene . . .
what’s with the breaks?
It's a component
you put it on a GameObject like anything else
look at a tutorial for switch statements. it explains everything . . .
WDYM by "manage" it?
Ok but how do you use it after that?
I just linked you the documentation
you interact with it through calling its methods of course
There's my problem, even after reading the documentation a couple of times, I don't understand how to use it
what are you trying to do with it
it's just there to give you the ability to convert to and from world space positions and grid coordinates.
that's all
I would like to use the grid to detect where is the player, walls and limits of the board at any given time so I can restrict movements
The main methods you will interact with are:
https://docs.unity3d.com/ScriptReference/GridLayout.WorldToCell.html
and
https://docs.unity3d.com/ScriptReference/GridLayout.CellToWorld.html
this seems like a wrong use of it
it's not going to "detect" anything
it will stop another case i guess
it was a long time i didnt use it
but if you dont use it
it will be broke
your game logic should simply take place on a 2d coordinate system
huh
the point of the grid is to just help you translate that 2D coordinate system into 3D positions @bitter valley and vice versa
break; will stop another case :0
So it would be better for me to find another way to use it?
well i’ve never seen break being used in c#
you should use it as I mentioned
to just help you translate that 2D coordinate system into 3D positions and vice versa
Yeah but right now I can't think of a way that would help me for the project I'm working on ^^"
ye thats right but its necessary for switch case statement
ok
I'm not sure how to help more than that
I think it seems obvious to me
Ok thank you for the infos 🙂
Not sure where to ask for help, I have world space UI that partially disappear when moving/changing resolution, looked into pixel perfect features but this requires screen space overlay and removes size scaling from what I understand
Is there a way to make a sprite brighter? I can set RGB so that the sprite is darker, but not brighter. Is that a feature of RGBA?
SpriteRenderer Color is multiplied by the base sprite colors
you can't make things brighter through multiplication, only darker
You'd need to brighten the original sprite asset
Interesting, thanks for the info
That was the back up plan ^^
If SpriteRenderer.color allowed for HDR colors, as in not clamped between 0-1, this would be possible. (and I think it should)
yeah not sure if it allows hdr or not
Isn't there something for that? On the sprite renderer's material
If your material allows for HDR colors, you can multiply it there too. But SpriteRenderer.color definitely clamps.
I thought so ^^ I'd rather not use material just for that, I'll work around it. Thanks 🙂
please help, unity says: error CS0246: The type or namespace name 'WebGL' could not be found (are you missing a using directive or an assembly reference?)
I created a function for enemy to shoot when the ray hit the player. Enemy is not shooting. The ray is not hitting the player despite of everything is aligned.
debug ur rays make sure they are where u think they are
show the code
can share code the right way #854851968446365696 dont screenshot code
sorry, of course https://gdl.space/mutotiriti.cpp
alr so where exactly did you see to use using WebGL namespace
explain
wdym 2 objects are webgl
webgl is a rendering engine
i think the problem is unity doesnt recognize webgl as it says it couldnt find it
wait
WebGL is a class at most.. Never seen WebGL in a namespace.
is that supposed to say InputField ?
where did you get this from...what is it for,
i dont know, the guy in the tutorial told me to lol
so you're copying things you don't understand?
well how am i supposed to learn
show the tut..
im just learning
CryptoGrounds: Coding and Gaming, for Everyone!
Hello! In this video, I will be showing you guys how to make our import and export system supported for WebGL builds.
WebGL is a Javascript API used for rendering 2D and 3D games on the web, which is what Unity uses to run its games on the web!
Currently, normal input fields are not accessible i...
IEnumerator EmitRoutine(ParticleSystem.EmitParams @params, ParticleSystem.ShapeModule shape)
{
print("starting emit routine");
float timer = 0;
print("time at emit start is " + Time.time);
float timestart = Time.time;
float particleDur = ParticleDuration * 60;
print("particledur is " + particleDur);
while (timer < particleDur)
{
shape.rotation = TargetTransform.rotation.eulerAngles;
@params.position = TargetTransform.position;
Particles.Emit(@params, ParticlesToEmit);
print("timer is " + timer + " at " + (Time.time - timestart));
yield return new WaitForSeconds(EmissionRate);
timer += 60 * EmissionRate;
//yield return null;
}
print("time at end is " + Time.time);
float timediff = Time.time - timestart;
print("time diff is " + timediff);
print("emit routine finished");
}
I made this coroutine for intermittently emitting particles but the time difference is about 1 second longer than the duration I specified
I'm guessing I should rely on delta time and check if I passed a certain amount of seconds instead of relying on waitforseconds?
WebGlNativeInputFields must be custom components
so, what now?
follow a better tutorial ?
these dont teach you shit tbh
just "do this and this and this , now ur done"
how did you learn
i learned the fundamentals before ever watching videos like this
having a configured IDE
etc
idk I've made many WebGL projects, never Did i have the need for WEBGLNativeInputs
this some weird shit rn
oh btw, what am i supposed to do with this
you are in #archived-code-general and said know the fundamentals. I expect you should know how to proceed next
yes, i know the fundamentals, but could you please elaborate
talk about a contradiction...
do you want me to hold your hand the whole way, If that is the component then you add it in..
just like you add any other custom component
what component?? you sent me a github link
the last one?
dawg you know the fundamentals and cant even read the description of the video ur watching ... comon dawg make an effort
they even link the package u need in description..
then you didnt install it correct, you should be able to see the component
ur intellisense in VSCode is not even configured...
how would you even know if script is reading the component..
did you put this folder in Assets ? @echo steeple
yes
can u show it shows up in Add Component in inspector
ok so now fix the spelling
this isnt addComponent
"I know the fundamentals"
you see why it's annoying when ppl lie
i have no idea what you mean 😟
its unity 101
look itup and come back when you know what inspector and add component button is
and please stick to #💻┃code-beginner next time..
uh oh. i see you are trying to do something impossible
are you trying to have a text input field on a mobile webgl game?
its not mobile
hmm
why aren't you using a regular input field?
if you have input system handling set to both, it works.
i can add that to my tips and tricks
ok i think i can do that without breaking the game i will try
does anybody know a tutorial for a 2d bomb explosion tutorial? I can't seem to find except for one which won't work.
the underlying issue with input fields on webgl and many of the odd platforms is that tmp_inputfield and inputfield both use IMGUI Event to poll characters instead of input system. @heady marten but yet again, the cantankerousness of ticketing all of this and getting to a conversation with a unity engineer that isn't sales-led is so dire
it works!(for now '~' ) thank you for actually helping ^.^
(and putting up with my stupidness)
I'm researching showing html elements over a full screen web unity instance but can't get things working. I'm unable to find a way with absolute position and/or zindex. The elements render on top of the game when not in full screen, but disappear once the game is full screen... has anyone done this before?
no problem
@echo steeple you can take a look at my forum thread https://forum.unity.com/threads/tips-and-tricks-for-using-webgl-on-desktop-and-mobile-tested-up-to-2021-3-11f1.666121/ for more info about webgl
sure ^.^
how can i setup vs code to work with unity?
#854851968446365696 has a configuration guide
Just look for creating a bomb tutorial, or an explosion tutorial. Don't be too specific. Anything else you need, like a timer, etc., you should search for separately then combine them together . . .
pretty simple, unless you’re asking about the explosion effect itself
Hello, I would like to ask
I'm drawling lines with GL
why does it only show when gizmos is on?
in game view
Are you calling it in Update or something?
Check the documentation for a code example and the appropriate place to call GL functions:
https://docs.unity3d.com/ScriptReference/GL.html
anyways, I'm calling it in OnRenderObject
I know that if u put it in camera, it's OnPostRender(), but I need to easily change it's place
so I opted for gameobject
the gameobject
Can you show the code?
hmokay, it's pretty long thoguh
#854851968446365696 for how to share code here
sure
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.
here's the code
the function responsible for drawing the lines is
drawLines()
o, I did do it in OnDrawGizmos()
my bad'
but why didn't OnRenderObject works?
okay, I am gonna check
Idk the docs are confusing. They say one thing and the code example does something else
GL isn't talked as much, sad, so I harder to find wha ti Wnat
yeah, OnRenderObject isn't being called
alright
okay, turns out it needs a renderer
How do you name tags in git? v1.1.1?
what about if you build your app for several markets? market/v1.1.1? market-v1.1.1?
I prefer v1.1.1 but how I can distinguish them between markets?
Should they have same version?
I should've checked properly before asking, oh well
Let's say we're making a large number of, let's call them pokemon-style attacks
Lots of moves that can alter the battle in as-of-yet unpredictable ways, such as damaging, applying status effects, modifying stats, creating ongoing passive effects, placing traps, etc
The point is that I need to be making a lot Nouns that will each be performing multiple Verbs that may affect an ever-growing list of types of Nouns
And I'm trying to figure out how to represent that
Right now I'm imagining a few- or potentially a lot- of ScriptableObjects all inheriting from the same base class that represent actions, potentially even ScriptableObject scripts that are only expected to be used once since their exact effects are so specific
But I'm having trouble working out the nuances of having all that polymorphic behavior, with many different function signatures, often requiring state information about the battlefield, be represented as something I can pass an entity as like, a list of Actions they're allowed to take
I guess more specifically each "Action" could be made up of multiple "SubActions" performed at once (attack, modify stats, inflict status effect) so as not to have to make an SO script for each fiddly combination, but details, details
yeah the way I do this is prtty generic and doesn't use inheritance at all.
A few pieces:
- an enum for "effect type" (e.g. damage, chance to inflict status effect, etc..)
- an "Effect" object. It's basically an EffectType + a number.
- An attack just has a list of effects.
So a particular Attack would be something like:
Fireball
pp: 10
effects:
- Damage: 50
- BurnChance: .5
Then to execute this you just loop through the effects and each enum value is mapped to a function. You can essentially think of that just as a big switch statement
you can easily mix and match any list of effects you want this way
Then it's just one ScriptableObject per Attack (The SO has a name, a cost, a PP amount, and a list of Effects as above)
fixed ( for URP user ), Solution: https://answers.unity.com/questions/1545858/onpostrender-is-not-called.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.
I suppose I am having a hard time coming up with a "weird attack" that couldn't in some manner be put in a list of status effects or a list of Battlefield Effects
Do you ever feel like that central system which executes those effects could grow big enough to be cumbersome?
nvm, not fixed lol, it's fixed in game view in unity but not fixed in .apk in andorid
Yes but that system could be modularized somewhat easily.
It might get weird with multi turn attacks, something like... Dig, or Fly? You'd probably have to model that as putting a status effect on yourself, and then handling the delayed attack kinda weird, right? You'd have to pass the stats for the attack to the code that later executes the "delayed" attack part
In my case I'm using my system for a tower defense game
Mmhm
Interesting. Yeah, this should work.
Hey, it's been months since last time, but I always see you around here and it's always really helpful talking through things with you. Thanks for that.
You'll also want to think about how to handle "typed" damage, and things like "status effect type". It could either be different effect types, e.g.:
- Fire Damage
- Electric Damage
- Normal Damage
etc...
OR you could add a third field to the Effect which is like a "tag".
So you'd have e.g.:
EffectType: Damage, Amount: 50, Tag: Electric
or
EffectType: StatusEffectChance, Amount: .5, Tag: Burn
Something to think about
assuming that matters in your game
Mmhm, we'll see if I decide to go forward with implementing that
I am notorious for complaining to my friends that elemental damage in games like D&D and Dark Souls are mostly pointless and not a fun moving part to deal with
Hey everyone,
I need help with disabling my parallax effect in Unity when my screenbox is disabled, so it doesn't disrupt my UI. Tried using SetActive() and disabling components but nothing seems to work. Any Idea? I'm sending the code 😄
using UnityEngine;
using System.Collections.Generic;
public class ScreenBoxManager : MonoBehaviour
{
public GameObject frame1;
public GameObject frame2;
private void OnTriggerEnter2D(Collider2D collider){
if (frame1.active == true){
frame1.SetActive(false);
frame2.SetActive(true);
//disable parallax layers
var parallax = GameObject.Find("ParallaxBackground").GetComponent<ParallaxBackground>();
foreach (ParallaxLayer layer in parallax.parallaxLayers)
{
layer.gameObject.SetActive(false);
}
} else if (frame1.active == false){
frame1.SetActive(true);
frame2.SetActive(false);
//enable parallax layers
var parallax = GameObject.Find("ParallaxBackground").GetComponent<ParallaxBackground>();
foreach (ParallaxLayer layer in parallax.parallaxLayers)
{
layer.gameObject.SetActive(true);
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class ParallaxBackground : MonoBehaviour
{
public ParallaxCamera parallaxCamera;
public List<ParallaxLayer> parallaxLayers = new List<ParallaxLayer>();
void Start()
{
if (parallaxCamera == null)
parallaxCamera = Camera.main.GetComponent<ParallaxCamera>();
if (parallaxCamera != null)
parallaxCamera.onCameraTranslate += Move;
SetLayers();
}
void SetLayers()
{
parallaxLayers.Clear();
for (int i = 0; i < transform.childCount; i++)
{
ParallaxLayer layer = transform.GetChild(i).GetComponent<ParallaxLayer>();
if (layer != null)
{
layer.name = "Layer-" + i;
parallaxLayers.Add(layer);
}
}
}
void Move(float delta)
{
foreach (ParallaxLayer layer in parallaxLayers)
{
layer.Move(delta);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class ParallaxCamera : MonoBehaviour
{
public delegate void ParallaxCameraDelegate(float deltaMovement);
public ParallaxCameraDelegate onCameraTranslate;
private float oldPosition;
void Start()
{
oldPosition = transform.position.x;
}
void LateUpdate()
{
if (transform.position.x != oldPosition)
{
if (onCameraTranslate != null)
{
float delta = oldPosition - transform.position.x;
onCameraTranslate(delta);
}
oldPosition = transform.position.x;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class ParallaxLayer : MonoBehaviour
{
public float parallaxFactor;
public void Move(float delta)
{
Vector3 newPos = transform.localPosition;
newPos.x -= delta * parallaxFactor;
transform.localPosition = newPos;
}
}
If anyone have an Idea how to cancel the fact that my Layer are moving when the Box is inactive or help me find how to change the Axis position when I enter a new box, It would be really great !
what are frame1 and frame2? What do they have to do with the parallax things?
you've kinda dumped a ton of code here without context
frame 1 and frame 2 are two ScreenBoxes
and My problem is that when frame 1 is active, the Layer of frame 2 moves even if it's off
so I wonder I someone have an idea how to change the Parallax axis when the frame changes 😄
void Move(float delta)
{
foreach (ParallaxLayer layer in parallaxLayers)
{
layer.Move(delta);
}
}```
isn't this the code that's moving them?
yes it is
I don't see anything here that would care about whether the frame objects are active or not
well I tryied to check it with IsActive() but it didn't work either
I don't really understand what you're trying to do here tbh
why not just remove the ones you don't want to move from that list
I'm trying to have different boxes into a scene likeso they are not too many object and the player isn't lagging
because It's a general script for all my layers
maybe you need a separate list for "currently moving / active layers"
I want them to move but frim a different axis only when the box is active
I'll look at this, good idea
but it doesn't fix the Parallax Axis :c
It's not working either because my background Parallax is already different for each screenboxes so the script shouldn't be active when the script isn't active either
why do you have execute in edit mode set for these
they mutate their transforms... you don't want to do that in edit mode
that's not going to work
first remove execute in edit mode
before anything else
okk I used it to see where to put my colliders 🐸
you are also adding event listeners and never removing them in an executeineditmode script
which is really bad*
the delegate is not an event either. it doesn't have to be but that's surprising
well I removed them
onCameraTranslate is redundant
don't use an event at all
setlayers is also surprising
what is a screenbox? what do you mean a disabled screenbox?
a bunch of your issues are coming from this event
don't use them
it is surprising to you
well a screenbox is a box that have a part of the scene and is only active when the player enter inside it
It's usefull not to generate everything at the same moment
void LateUpdate() {
if (transform.position.x == oldPositionX) {
return;
}
foreach (var parallaxBackground in parallaxBackgrounds) {
parallaxBackground.Move(transform.position.x - oldPositionX);
}
}
don't use the delegate, it is what is causing your issue
the delegate ( the event) is still going to execute even if a game object is inactive
but even without that my problem is about the parallax axis when I enter a new place because It keep his first position and don't know how to change it
well
a lot of the problems you are having are Programming
you have to deal with all these issues
haha
nobody said parallax would be simple lol
Okk, will try to find my issues this evening then
Android question here, I'm trying to use the System.IO to read the filesystem on an Oculus Quest.... but I keep getting permission error. I added the code below into the AndroidManifest.xml but I don't see the pop up for permissions when I launch in debugger and I still get the Permission denied error.... What could I be missing?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
what part of the file system are you trying to read from?
also WRITE_EXTERNAL_STORAGE seems like it's for writing only
what about reading?
I don't think any app is allowed to read/write to / under any circumstance in Android
yes, they are
The Quest 2 is running Android 10, tried including android:requestLegacyExternalStorage="true" but still doesn't have the permission pop up
are permissions supposed to pop up when running in debug mode?
I supposed if you only wanted to READ and not write?
wait..
what about it?
guess it is explicit with WRITE_EXTERNAL_STORAGE
I know it's possible to at least read root... Skybox VR does it and I know that's running unity
granted, it has the permission pop up when you open the app
doesn't package manager take care of permissions ?
which is from the AndroidManifest.xml..
do you have to grab those values from the manifest ?
the OS grabs it
ok so they're injected in but don't you still have to make a request on whatever components you declared wanting permission from
I have changed my strategy and instead using ray now I am using viewPort to check if the enemy is visible in the main camera or not. if it is visible it should start shooting to the player. But it is shooting even when it is not visible in the main camera.
I'm seeing this pattern often
hm... I could try to verify if it's working... but I'm wondering if I'm misunderstanding what WRITE_EXTERNAL_STORAGE means here. I just found this in the player settings
I've only exported to APKs to playtest, never actually messed with permissions tho 😫
you can try your luck in #📱┃mobile
did you read through this ?
https://docs.unity3d.com/Manual/android-RequestingPermissions.html
looks like unity took care of the methods and have a Permission class..
When detecting collision with OnTriggerEnter() is it possible to check the layer of the other collider or would it be more performant to just use tags and CompareTag()?
Probably doesn't matter much
Unless you're doing some extremely whacky major collision events
Mostly for differentiating things like hitting a wall, character, boundary, etc
In which case you should use the profiler to determine it
Yeah that really won't matter performance wise
Unless you plan on building an absolutely massive game
is there a way to cut out part of a block without editing the model file obviously
This is for a (networked) projectile system so I'd like to make it as performant as possible.
I have already stress tested it with a shotgun that shoots 100 projectiles 10x a second in the past.
this iteration should be a lot more performant on the network side too
I disabled the on hit effects in this video
But you can see all of that info going over the wire no problem
The sort of square ish breaking on the end has to do with tick rate
In general players wont have more than a few dozen projectiles active at once
Hi guys, somebody can help me with this error please?🙈
Try Window -> Layout -> pick one of the presets
It's not an error. It won't break anything, but if you want to solve it, reset your window layout.
public GameObject LoadoutButton;
public GameObject[] LoadoutButtons = new GameObject[20];
public override bool Active
{
get => base.Active;
set
{
base.Active = value;
if (value)
{
List<byte> notNullindexes = new(), Nullindexes = new();
for (byte k = 0; k < LoadoutButtons.Length; k++)
{
if (LoadoutButtons[k] != null)
{
notNullindexes.Add(k);
}
else
{
Nullindexes.Add(k);
} // player.playerData.LoadoutDatas.Count is dynamic, could be 20 max
for (byte i = 0; i < player.playerData.LoadoutDatas.Count; i++)
{
}
}
}
}
}```
I'm trying to create buttons based on player.playerData.LoadoutDatas.Count
to avoid any index out of range errors, I've instantiated LoadoutButtons' size as 15 and made two Lists that contains null/not null indexes separately
what's the question
and why would the array contain null elements?
basically creating player.playerData.LoadoutDatas.Count amount of LoadoutButton gameobjects
and remove the extra ones if LoadoutButtons has more buttons than player.playerData.LoadoutDatas.Count
What part are you struggling with though?
Use Instantiate(somePrefab) to create them
Destroy to destroy the excess
Just put them in a List
not sure what all this nullIndexes and nonNullIndexes thing is about
Don't use an array when you want something resizable
oh one more thing, the most important part
I'm trying to keep the button indexes fixed
that's why I did that list crap
not sure what that means or how it's related
why would the indexes change?
also why byte for the indices 😵💫
yes
basically the create a class system from call of duty
trying to replicate it
Probably explain your approach
I would have used SO or something for the data then utilize it under a separate place
alright so I have these scriptable objects with a LoadoutData struct
public List<LoadoutData> LoadoutDatas = new List<LoadoutData>();``` got this
created 10 of them
but this amount may change
so I'm trying to make a UI system that will bring me the right amount of buttons related to those LoadoutDatas indexes
each button will open the respective LoadoutDatas
the simple approach is something like:
MyButtonScript buttonPrefab;
List<MyButtonScript> buttons = new();
void SetLoadouts(List<Loadout> loadouts) {
for (int i = 0; i < loadouts.Count; i++) {
MyButtonScript theButton;
if (i >= buttons.Count) {
// we need to add a new button instance
theButton = Instantiate(buttonPrefab);
buttons.Add(newButton);
}
else {
// we already have an instance in the list.
theButton = buttons[i];
}
theButton.Initialize(loadouts[i]);
}
// now make sure we don't have any _excess buttons_
while (buttons.Count > loadouts.Count) {
Destroy(buttons[buttons.Count - 1].gameObject);
buttons.RemoveAt(buttons.Count - 1);
}
}```
that's why I'm trying to keep the indexes of buttons fixed while also making the resizable
omg you're a magician
thank you
I've been going nuts about this
thanks to everyone else as well
Does anyone know a way to test if the z component of a normal map in unity is flipped automatically?
"normal map" is typically a texture used for "bump-mapping" in a shader/material. Are you talking about detecting if the normals of a mesh are inverted?
no
I have a few normal maps but one is different from the others, for one of them to be correct in my program I have to do 1 - its z component
unity seems to handle this automatically and idk how
No idea. I feel like that'd be in the realm of like "Is there a way to tell automatically if the colors of a texture are correct?". Aren't all textures "correct"? It just depends on the intention, which the computer cannot know.
thats fair
I just dont know how I can feed 2 normal maps to unity standard shader and they both display one thing
but if I use my compute shader project thingy to display them one of them has its y component wrong
that's a really good question and I have no answer for you
is the z component ignored by the standard shader maybe?
(you said z above and y here so not sure which you mean)
sorry I mean z
since y is up in unity, I ignore that component
also theres no way to get like dxt render textures right? I need to compress these runtime created atlas's so that they aint like 3 gigs each
I keep on getting this error that says that the enemy's script is destroyed, and to check if it is null, so I did that, but it still gives me the error and idk what to do
//Stuff called from Actions
void ChangeEnemySpeed(float change, float timeUntilNormal)
{
float initialEnemySpeed = enemySpeed;
if (gameObject != null)
{
enemySpeed *= change;
StartCoroutine(speedToNormal());
}
IEnumerator speedToNormal()
{
if (gameObject != null)
{
yield return new WaitForSeconds(timeUntilNormal);
enemySpeed = initialEnemySpeed;
}
}
}
what is line 100 ?
starting the coroutine
StartCoroutine(speedToNormal());
wired
what object is that script on?
can you log what gameObject is in that case ?
so is there a way to create a texture2d without causing a freeze?
why would the game freeze unless you are createing some Exteme big textures
16k
i notice if i create a rendertexture it doesnt freeze for a second but if I do a texture2d it does
CPU VS GPU menory?
I need texture2d instead of rendertexture because its much faster to sample a texture2d in a compute shader for some reason
hmmm
the gameObject is an enemy that has the script attached to it
is there any reason the object could be destroyed when you are running that code?
I just checked right now and it only happens when the enemy dies (it gets deleted)
mmm i currently see any good work arround if you cant work with a set of smaller textures
but would that not matter since I already check if its null?
I cant because I cant send an unknown amount of textures to the compute shader
cuz unity doesnt support bindlesss...
im not 100% sure the issue might be that the corutine does not directly runs when in update but after upadte
if the object is destoryd in the mean time that might cause a problem
could you add a log in OnDestory to check that?
are you checking if it's null before you try to start a coroutine on it? What's the context around that call?
You might be right since I have a function in Update() that checks if health <= 0, then destroys the object
but then what should I do to make the Coroutine work then
dont destroy the object you want to corutine to run on
so would there be another way to do this then? since the enemy has to die if its health falls below 0.
or run the code on a different object
I did that but instead I got an error that it couldn't access the enemy script
so I turned to this way and used Actions
why would you have to deal with the enemy script if the enemy is dead?
It shouldn't
this function is called when one of my power-ups stuns the enemy it hits
so it shouldn't work against enemies already destroyed
you could stop the corutine when you are destroying the object
that would get rid of the error
like StopAllCoroutines()?
that one option
or you save the Coroutine to a variable that you then can stop it via that
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html
k thank you
hey, so i have a floppy bird game where pipes are spawned every 3 seconds. i also have a powerup spawning on random timer, how can i make the powerup always spawn right between the pipes
How big is your terrain? might be imprecision, try breaking it up into smaller chunks and rebaking
maybe do a casting with rays, if the area is free then it should be spawned as that would prob be between pipes, clamp the Y pos in a range
if the pipes are every 3 seconds then only spawn a powerup if a timer counter mod 3 == 0
Maybe add a little wiggle room since it's unlikely to be exactly 0
welp i want it to be roughly in a middle an that should be enough, i just dont want it to spawn on the pipe
so i could potentially spawn it only when, say, pipe counter is equal to 1,5
You could add an empty transform in between your pipes that is exactly where you want to spawn it
then if you're rng dictates to spawn a powerup, go ahead and spawn it using the empty's location
Depends . . . Are your pipes a) ways the same distance apart or are their small and large random gaps between them?
welp theyre roughly always the same, theres a very simple counter spawning the pipe when it hits 3 and then resetting
The counter is irrelevant, we just need to know if the distance between them changes or not, e.g., when I made my clone, I had a min and max distance between them . . .
nope its always the same
oh i apologise for misunderstatement, i ment between the pipe clones
so in a free space from before another pipe spawns
Yeah I'd try smaller sizes if possible. I've had that frustration before of little gaps
if space stays the same then my pic doesn't matter, just use an empty gameobject position
space between bottom of rect and top of rect
also, just as a side note, would that have a chance to work?
it will move up and down with the prefab clone
i actually dont want it to spawn between top and bottom pipe, i want it to spawn horizontally in the middle between one pipe and another
if that matters
raycast and call it a day
so basically like this
well more in the middle but yea
alright i can try
Anyone know why line 42 and 43 never run?
https://paste.ofcode.org/TfLt8pJHaY4d3HucgLPxv
looks like they're inside an if statement
presumably the condition is false
i already checked that and the Debug.Log("running"); runs
they're also after a yield
so it has to do something with the yield return new
a coroutine won't resume from a yield if the object running it is destroyed or deactivated
That would be true but it doesn't even work for objects that aren't destroyed
so presumably your object is being destroyed or disabled
also check how long stunTime is
it's also kinda weird to use a local function for this
Ok so... which GameObject is this script attached to
an explosion that appears and disappears after a short amount of time
could it be because I Destroy() it after a second?
yeah that was the case
I literally asked you that lol
and you said it wasn't destroyed
or rather you said this which is kind of a non answer
I thought you meant by like the enemy that it is colliding with was being destroyed
that doesn't seem relevant but alright
Hey im just trying to figure out how the save/load work flow works. I can turn all my objects into json and stick them in a string list but then how do i store the list of json strings to be read in by the loader?
list of json strings? Wdym by that?
please help me
The general idea is you put all of the data you want to save in a big object like:
[Serializable]
public class SaveGameData {
// whatever data you want to save goes in here. ALL OF IT.
}```
Then you just feed that object to the serializer and it gives you one json string. You write that string to your file. Done.
then reverse it to load
I was planning on having the loader read through the list and create each object, or is there a better way of doing that
you can do that but then put them all in a list
and throw them into the main save data object
[Serializable]
public class SaveGameData {
// whatever data you want to save goes in here. ALL OF IT.
public List<Whatever> whatevers;
}```
your loader can read through the whatevers list and instantiate GameObjects or whatever it needs to do
but you can use JsonUtility.toJson() on a list
You can use it on an object that contains a list
like my example
you can't use it directly on a list.
huh, ok so i would be creating a group object and json-ing that?
yes
your save/load code need not be any more complicated than:
string json = JsonUtility.ToJson(saveData);
File.WriteAllText(json, filepath);```
and
```cs
string json = File.ReadAllText(filepath);
SaveData loadedData = JsonUtility.FromJson<SaveData>(json);```
that just seems like more work to then have to decode the object then decode the data within that object, i feel like writing each on to an array would have been a faster way to save it to a text file
what lol
This is more work?
loadedData.whatevers < this is not work
this is one .
Work would be some crazy string concatenation scheme you probably are about to try
work with the parser, not against it
there's no further "decoding" to do
alright, Thanks! in Gamemaker I ended up having to make my own save format with nested arrays cuz it wouldn't support structs taking variables
do you mind if I ask, why are you always in here? Every time I come to this discord you are always on answering tons of questions in multiple channels. Is unity like paying you or are you just super motivated to help people?
or are you even real.... 🧐 just a super smart Q&A AI
procrastination
they should be paying me
tell them to pay me
LMAO!
I'm working on an asset store asset right now and my code isn't working as i'd like it to so instead of fixing it I'm in here fixing other people's shit
I felt this on a peroneal level lol
That's mastery right there. I hope to achieve this level of productive procrastination some day
So I'm writing a netcode framework and I'm working on audio, but I have no idea where to start. Looking for ideas.
If I literally roll back the audio source state, and fast forward it's time attribute during the rollback stage, do you think the audio will be poppy or glitchy?
There's like nothing on the internet about this stuff
would it help if I told you the asset store asset is itself procrastination from my day job?
How does audio relate to the netcode? Would audio not just be done completely locally?
Or are you talking about... voice chat or something?
If I shoot my predicted gun, the state has to be rolled back
generally guns have a shoot sound
basically everything in my NetworkFixedUpdate() loop gets rolled back
so right now it would basically just play a bunch of overlapping sounds
since I don't know how to properly rollback audio
you just dont play the audio while replaying from a rollback
I don't think you can really "roll back" audio but you can stop the clip that's playing in progress
Yeah I thought about just skipping new audio playback during rollback
but how? Without a code generator?
If I disable the audio source, currently played audio stops playing even when re-enabled
I feel like you as the framework author just need to notify the user that their state was rolled back somehow and handling the audio consequences of that are up to the user
I mean I could include in the documentation that you need to wrap your audio.play in a if (!Networking.isrollingback)
that just seems sort of gross
usually you literally have a boolean for your game state logic like "isReplaying"
alright yeah
I guess that works
Does Physics.Simulate() also tick particle systems?
the particle systems have their own Simulate() so I'm gonna assume it doesn't. The docs just don't state anything about it
probably not
Good news, I decided to actually debug my code and fixed it.
Hey, Congrats!
How would you like it to move instead?
I have a weird issue with Gizmos, as I'm trying to draw spheres in a circle, but at certain intervals they start not drawing a full circle, where did I mess up the maths/code?
(the third pic shows up how it should be)
You should make sure your divisions always use floating point maths
@void basalt Some ideas: You could have some sorta effects manager that you trigger your effects through. (sfx, vfx whatever you dont want to replay during a rollback). It could track the ID of a sfx and the frame it was played,
when you do a rollback and replay through the frames it will have the info to know that an sfx of that id was already triggered on that frame, so ignore it.
oh, so I just gotta add the "f", right?
360 should be 360f, yes
it works now, thank you!
I always forget about adding it
dont crosspost next time :p
I definitely considered doing something like this as well
I wonder if its possible to directly alter the unity API. Like run some custom code right after AudioSource.play gets called
Unless you have the The Enterprise license(I think), you don't have access to the source code. At least not to modifying it. So, no.@void basalt
I read somewhere that the Mirror framework does some weird shit internally where they inject code into method calls, in order to give them networking functionality
all on a dynamic basis
No clue about it. If you have actual link to that info, maybe we could figure it out.
https://mirror-networking.gitbook.io/docs/guides/communications/remote-actions
Commands functions should have the prefix “Cmd” and cannot be static. This is a hint when reading code that calls the command - this function is special and is not invoked locally like a normal function.
I think you have to have access to the actual method body in the first place, so that might be impossible for what I'm trying to do
So im sending data to unity through a serialport with an arduino, although while reading the line, it appears to be either reading it twice or somehow getting another line (which is giving me errors about the index being out of bounds)
I just want to point out that's some level of commitment. Can we be your rubber ducky? ❤️
Throw some code on a page someplace, and we can see if there's any obvious software issues, but it's always possible it's hardware which would be harder to detect.
Couldn't you just inherit your class from AudioSource component instead? Or is that class sealed?
Or why not OnAudioFilterRead()?
Heh; one of the things about hanging out here and helping out is that it always makes me feel better about my own work when I'm around folks who are intent on building things. It's a virtuous cycle, somewhat. But I do look forward to seeing what it ends up being.
Well, im printing the data in the arduino ide and it comes out fine, when unity reads the code, it reads it fine, but also gets another set (of a shorter array) from I have no clue where
Im in a bit of trouble here
So it logs 2 entrys, the main one which is right, then a second one that is just wrong and im not sure where its coming from
Its kind of hard to explain but I'll try
I have a rectangle right, and I'm trying to set the variable LoadingBarObjX to the rectangles current size, so I have it getting set every frame, however I also want to subtract a value from LoadingBarObjX and apply the new value to the rectangles current size
However it seems due to LoadingBarObjX constantly getting set to the current size I can't subtract the value
Buffer overflow?
Actually might've just found something
Well, I figured out the issue, just not sure why the issue occurs, I have 2 if statements that shouldn't be active, but for some reason, those not being commented out sends a shorter array in the debug log
But the thing is, the thing they send to the debug log isn't even what shows up
Debugging: Why doesn't this work? Ah! I see the problem! Wait... Why did this EVER work? 😉
Ah shit nevermind still doesn't work
Yea true, but im honestly confused because why do 2 if statements not being commented out send an extra array to the debug log?
No clue; haven't seen the code. 😛
Anyone got any ideas for me?
The two debug lines at the bottom?
Yea, if I have those there, it adds an extra 0,0 in the debug log (since the above debug log sends 0,0,0 (or some version of 3 numbers)
me reaping: "I don't need to make these classes and function calls flexible for a wide range of uses, i'll just code up specific ones as needed. I'll be able to get moving faster, I'll come back and refactor them later!"
me sowing: "Aww man I did Step C like 5 subtly different ways, now I really need to refactor this code to cover the core use cases in a generic, reliable way"
I am beyond confused, I have variable LoadingBarObjX set to 1 and an if statement that should activate if LoadingBarObjX > 1 however when I put LoadingBarObjX > 1 in the if statement it doesnt work, what does work is LoadingBarObjX < 1
Does sp.ReadByte block? Maybe you're running into something weird about Update being called while it's blocked... Because your if statements do have side-effects...
I mean, I thought if the if statement was false, it would just do nothing, not send a random debug like that
I think you have those backwards; unless it's a subtle threading joke. 🙃
No, I think you misunderstand... sp.ReadByte is blocking...waiting for a byte...reading it... The byte is zero (or a string zero, which is not equal to 1/2), so it skips out, but it read the byte so it's not in the stream anymore so the next update it reads fewer bytes.
Ah I see
naw i implemented like 80 various game commands in a only vaguely generic way and now it's like, oh i really should use the strategy pattern to configure this rather than custom classes that are 80% the same for everything.
Alright I figured it out for some reason the script thinks that the localscale x is negative
Is there a way to only activate a method when the script is added to an object? Not when the scene loads or anything ONLY when the script is added to an object, I want the method to be run once and that is it
Alright well I got it working how I want it
No there wasn't an easier way to make a loading bar fuck you
My loading bar is best loading bar
how to check if a List<T> is a list of any type (or a HashSet, Stack, etc)?
What exactly are you looking for
Do you want to know if it's an IEnumerable?
An IList?
An actual List?
oh jeesh lemme try to remember 😛
shorts answer is I wanted a List of lists where each individual list may be of a different <T>
List<IList> would do it
gotchya!
IEnumerator EmitRoutine(ParticleSystem.EmitParams @params, ParticleSystem.ShapeModule shape)
{
print("starting emit routine");
float timer = 0;
print("time at emit start is " + Time.time);
float timestart = Time.time;
float particleDur = ParticleDuration * 60;
print("particledur is " + particleDur);
while (timer < particleDur)
{
shape.rotation = TargetTransform.rotation.eulerAngles;
@params.position = TargetTransform.position;
Particles.Emit(@params, ParticlesToEmit);
print("timer is " + timer + " at " + (Time.time - timestart));
yield return new WaitForSeconds(EmissionRate);
timer += 60 * EmissionRate;
//yield return null;
}
print("time at end is " + Time.time);
float timediff = Time.time - timestart;
print("time diff is " + timediff);
print("emit routine finished");
}
I made this coroutine for intermittently emitting particles but the time difference is about 1 second longer than the duration I specified
I'm guessing I should rely on delta time and check if I passed a certain amount of seconds instead of relying on waitforseconds?
Or is my math wrong?
Anyone has code examples on how to update a mesh using the new API every frame that varies in #vertices? My concern is I'm not sure if I should recreate the VertexAttributeDescriptor each frame and set it via SetIndexBufferParams/SetVertexBufferParams, or there is other better ways. Would be nice to see what the optimal way of doing this.
Your math is a bit wrong, but I would do like you said
You'd have to take into account that WaitForSeconds is not super accurate, and typically is slightly delayed by a few ms
I don't see what EmmisionRate is, but if this is very low, then eventually this may add up
Does anybody know where I can find a big list of Unity Exceptions?
emission rate is supposed to be a fraction of a second
like .1 for every 10th of a second meaning 10 particles every second
i am trying to load asset bundles from the server and now it downloads every time i open game any solution for this?
Timing in IEnumerable is inaccurate
If you want it to be accurate, rely on Time.DeltaTime within Update
You can replicate a second by doing something like this:
float _interval;
void Update()
{
this._interval+= Time.DeltaTime;
if (this._interval < 1) return;
_interval -= 1;
// Behaviour here
}
_interval -= 1; is important as setting is to 0 can still make it inaccurate, since it's never going to be exactly 1 second
I think this is as accurate as you will get it
I have a problem that I can't come up with a good solution for. Basically I have scriptable objects for my weapons, each weapon has a set of abilities it can perform. The problem is that some of the ability properties should come from the editor, such as icon, description and cooldown so you can easily change them without diving into the code, while the name and method have to be set through the code because I can't expose the method (it can't be a UnityEvent because I need a return type other than void). The issue I'm having is that if I create the abilities list in the constructor any changes later after the scriptable object is created it won't obtain. Equally with the OnValidate I have to check for existing abilities in the list before I attempt to add them or replace the list entirely, otherwise I will always lose info that I set via the editor.
One way I could work around this would be to have a separate list altogether where you specify the icon, description and cooldown which are then mapped to the abilities list. However I don't think this is optimal either if the abilities list changes then the lists would be out of sync instantly..
Does anyone have a good idea how I can approach this?
Don't think you can do it with modulo?
But yeah there are other ways. This is just what I thought of
yeah can't, i was just overthinking it
You can probably use Coroutines in some way too
while the name and method have to be set through the code because I can't expose the method
wat? This sounds like you're over-generalizing your weapons...
@frigid anvil Not sure what you mean by that?
What do you mean by 'I can't expose the method'?
@frigid anvil Well if I could I would, but I can't get it to show up in the inspector without using UnityEvent, since I need bool as a return type and not void I have to use a custom delegate:
public delegate bool MethodAction(BaseController caster, BaseController target, bool canPerformAbility);
public MethodAction method;
public AbilityInfo(MethodAction method, ... other stuff)
{
this.method = method;
...
}
Which is then used like:
new AbilityInfo(nameof(Stab), Stab);
...
public bool BasicAttack(BaseController caster, BaseController target, bool canPerformAttack) { ... }
Right, so you're trying to generalize your weapons to have an arbitrary list of abilities that directly correspond to different internal methods. That's what I meant by 'over-generalizing your weapons'. Why not have a single Attack(...) behavior for each, instead, for instance? That would allow you to eliminate some of the complexity which is causing you trouble in your question.
Just remember it's never exactly one second since you will always be frame depentent. So _interval can end up as 1.1 for example, because Time.DeltaTime was around 0.1 because of a lag spike, but there is no way around that as far as I know
Well for enemies that is what I have and it works great. However, since player combat requires a UI to go along with it this is what is causing the issues. Enemies can simply perform their attacks since they're automated, but players have to manually cast abilities to perform the attacks, which is done with clicks on buttons in the UI.
Hey, got a question about code design. I'm struggling to think of a way to make my character not move because there's so many reasons why he shouldn't move. I initially had one boolean, but that doesn't work very well since multiple scripts interacted with it, for example quitting a dialogue would make him move while the player was still in a cinematic part. The way I make it work now is to have lots of booleans for the check on the condition, like if(inTransition || inDialogue || ...){movement = new vector2(0,0)}, but it's still very confusing. Any tips on how to make it simple?
So...for instance, a player's gun would have...'shoot' and 'bash' options? I'm trying to see how it plays out. Also, what's the bool return used for, and is there some other way it can be communicated?
(there's supposed to be || instead of spoilers)
Yeah or a sword could have "stab", "slash", "swirling tornado" etc etc. The bool is used to determine whether or not the attack was actually performed or not, which I can then act on:
bool didPerformAbility = abilityToPerform.method.Invoke(GameManager.instance.player, currentTarget, CanPerformAbility);
if (didPerformAbility)
{
if (abilityToPerform.cooldown > 0)
{
PlaceAbilityOnCooldown(abilityToPerform);
}
...
}
I'm trying to think if the CanPerformAbility logic should be refactored out of each ability though.. that way it could be possible to skip the return type because the ability would always be performed.
So why isn't this bool didPerform = weapon.performAbility("ability_name_as_a_string", currentTarget, CanPerformAbility); ?
...and then leave it up to the weapon's performAbility code to figure out which ability to do? That pushes the behavior to...where the behavior lives, really, instead of pushing the complexity of behavior to...everywhere else.
Just to be clear, I'm brainstorming with you, because you called it out as a problem you were having trouble coming up with solutions for. I don't want to question or undermine your design; if that's how you want it, that's how you want it. Right now I'm suggesting alternatives that might better fit with the rest of the system you're describing, but if that doesn't work for you, say so.
can we trigger bake lightmap with code?
@frigid anvil Yeah that is fine, usually if I run into a wall I have to do a complete rethink of the design which usually works out. I can't remember why I baked it into each ability to begin with, will check the possibility of breaking it out again.
Yeah, me too. 🙂 When I get to a certain point, I'm like... 'Wait, what were my assumptions again? Are they still true?' And the one that kills me every time is, 'Do I really need that much flexibility?' I gotta stop writing mini-languages. 🤣
@frigid anvil That rings too true.. 🥹 Trying to future-proof your code is not worth it I've found, still struggling to get the habit out of my system but I'm slowly getting there...
is there a way to save a dictionary to a json file?
You could use json.NET to do this, Unity's JSON system doesn't support dictionaries and I'm unsure if you can create contracts for it https://www.newtonsoft.com/json/help/html/SerializingCollections.htm
https://www.newtonsoft.com/json/help/html/serializedictionary.htm
Newtonsoft's JSON utility does support it by default it seems. Never used it though.
https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@2.0/manual/index.html
thanks both of you ill try out :)
I've used Newtonsoft's library; it's really good. Takes some getting used to, but I like it a lot.
yea ok
How do I make a LocalizedString with specific arguments through code?
How can we save the light state between scenes?
thanks worked perfectly
when you create different ScriptableObjects as .asset files, do the methods inside them also get instantiated?
holding methods on another regular class would be better I guess
Methods don't get "instantiated", they are just instructions, not objects
They have the methods that that particular scriptableobject class has
You can open the .asset file in a text editor if you'd like to see exactly what it's doing. My understanding is that Unity only stores a reference to the ScriptableObject script and the properties of that object. Methods aren't stored on disk aside from in your Script file
What are you looking to achieve?
ah great
I was trying to prevent methods from "duplicating" across instances and taking up more space
even if that's what's happening
Nah, Unity uses ScriptableObject asset files more like a template for how to create your class. Not a fan of scriptable objects, very convenient but not very well documented and it's hard to understand what they're doing under the hood
thanks
@autumn cipher If you have a method that doesn't require state then you can mark it as 'static', that way all objects will share that method.
thank you
No problem!
Do keep in mind though that having objects that encapsulate both state and behaviour is what OOP is all about. If you want a set of data containers to execute methods defined elsewhere against then I think thats probably closer to the ECS way of doing things.
do you think ECS is more organized than OOP?
As often in programming you don't get "more" you get "different".
I want to learn ECS but I fear that not many employers might want ECS from me
so I'm doing it the common OOP way
Last I looked at the Unity dots/ecs side of things it didn't feel very mature.
But that was like 3 years ago.
should be a lot better now but yeah, best to go with the stable way
ECS can be more performant, so if you want to build a strategy game with thousands of units on screen then ECS is a better fit.
Yeah; that's the whole, 'Build it the old way, because you can get more help with it. If you ever get to the point that you need ECS, then you'll know you need it, and be better prepared to change to it.'
what is a proper way to make a backup of the project, is it just copy pasting the folder?
I'll try implementing a networking solution so I wish to make backup in case it gets ruined
You should use version control, like Git
And push it to a repository over on GitHub
Git supports "branches" and your networking solution can be developed in a seperate branch whilst your main branch is left unchanged
Git is important for literally everything. I'm surprised you haven't used it.
Not just code related either
I actually tried once and failed miserably
or was it something else related to github? I don't remember
Yeah, version control is...pretty key. Even for test projects, if I get to more than one or two scripts, or I start customizing assets, then I create a git project, and commit regularly, even if I don't push it anywhere.
Dunno. Git should be pretty simple
Init in a folder, add a gitignore for the language you use, and done
Optionally create a dev branch and start development
You can't really go wrong with it. Just fix your mistake and commit the changes
I am adding line renderer in runtime. The thing is that line is purple since there is no material getting added to line renderer component. how to fix this
Or, you know, revert
Have a Material field and assign that material to the LineRenderer when you create it.
Git has...some pretty spectacular failure modes, but for simple use, it should indeed be...simple. Just...commit regularly, and make sure all your assets are tracked in it. There are publicly available .gitignore files for Unity that will be very helpful, because there are folders you don't want to track.
Is there a way to combine a UploadHandlerFile with the multipart form data?
var webRequest = UnityWebRequest.Post(requestData.url, new List<IMultipartFormSection>() {
// new MultipartFormFileSection("vanillaZip",await File.ReadAllBytesAsync(tempPath) , "0.0" + ".zip", "application/zip"),
new MultipartFormDataSection("version", "0.1"),
new MultipartFormDataSection("bundleHash", "asfasfas")
});
webRequest.uploadHandler = new UploadHandlerFile(tempPath);
webRequest.uploadHandler.contentType = "application/zip";
e.g moving from the FormFileSection to the UploadHandler. The file in this case is large (1-5GB) and the file section won't chunk or stream, requires the entire thing in memory
that would probably go in #archived-code-advanced
I should probably upload the resources on dropbox or something
nvm this is getting too out of topic
That's what git lfs is for, but yeah...
Like Cyberfox said, this is why Git LFS exist
You can make a pretty big repo, but not push files like this in a regular repo
Although you might get an email from them if your repo becomes too big
idk if they would allow a 10+ GBs repo, I'll just exclude the Resources folder and save Resources on somewhere else, maybe google drive etc
Why do you have a 100MB file anyway
how would i make a proper loading bar? because rn i’ve just got it so the dev sets how long they want it to load, how do i make the loading bar actually go based off how much has loaded?
Looks like a model file with textures embedded.
it's a 3d model stacked with animations I guess
I don’t even know if there would be a point in that because it seems like unity instantly loads everything
You would need to do the loading in a coroutine or async method perhaps
Well, otherwise it will load in one frame
What are you loading?
Scene you can load async and use the loading % to update the bar.
https://www.youtube.com/watch?v=YMj2qPq9CP8
This would help
Let's create a progress bar!
● Download the scene: https://www.assetstore.unity3d.com/#!/content/40756?aid=1101lPGj
● Written tutorial by Alan Zucconi: http://www.alanzucconi.com/2016/03/30/loading-bar-in-unity/
♥ Support my videos on Patreon: http://patreon.com/brackeys/
······································································...
also has percentage showing (optional)
Other loading operations you would need to manually compute how much you've completed and update the loading bar accordingly (in turn requiring it to be async to update the rendered bar)
I have a loading bar made just need to get it to go based off how much has loaded
wdym other loading operations? like loading scripts or something?
Yeah so look at LoadSceneAsync and AsyncOperation.progress
yeah the video also shows that near the end
E.g loading save files, generating map etc.
alright appreciate it
ohhh yea, idk how tf to save stuff in a script in unity let alone save files, idk how to stop unity from resetting the values in the inspector each time the scene is loaded and unloaded
which is kind of annoying but playerprefs is annoying to deal with and idk how else to do it
If you want values to persist between scenes, you can use DontDestroyOnLoad
Or another way of saving
does that include stopping and playing the scene in the editor?
Like entering/exiting playmode?
yea
damn
You can always learn to save data?
Make the data you want to save serializable. Use a serializer, e.g. odin serializer (free). Save the serialized data to a file. Or use some asset from asset store.
How do i have a method in my script only run when the script is added to a game object? onenable seems to also run it when the play mode starts
oh alright
Im pretty sure anyway. Been a while since I used that
oh alright nice
idk it seems like it’s what i need
alright well thanks for the help
Hi, is there a version of TryGetComponent where the output is a list/array of components? (e.g. used for getting all colliders from an object)
A bit like GetComponents
Nope, but you can just use GetComponents and a for/foreach loop. If none was found, theres nothing to loop thru
Yeah
I've a basic form of Snake, where the body parts follow the player head position using a Vector 3 List of positions - however, as I pick up body parts, the distance between the body parts and the head seems to increase. Any idea why that might be happening?
// Move body parts
int index = 1;
foreach (Follower body in Convoy)
{
int queuePosition = Mathf.Min(index * Gap, PosHistory.Count - 1);
Vector2 point = PosHistory[queuePosition];
Vector2 pointAhead = PosHistory[queuePosition - 25];
body.MoveFollower(curSpeed, point, pointAhead);
index++;
}
currently i am downloading the file which is in File format is there any way that we can change the format of that file in unity at runtime?
You are missing using statements? Your IDE should suggest which one you should be using.
If not, do you have the advertisements asset installed?
The piece of code you took must match the version you have installed in the package manager.
Are you following these: https://docs.unity.com/ads/en/ImplementingRewardedAdsUnity.html ?
So you do have the using statement then
This is getting rather confusing for me too 😅
I don't really know, normally you just follow the integration https://docs.unity.com/ads/en/UnityDeveloperIntegrations.html and it works.
Sorry, I can't help then. If you have the using statements, the package is installed, and the SDK is initialized that's all there is to it afaik. That last part isn't needed for it to recognize your interfaces. So I don't know 🤷♂️
Yeah, I would think that means he added them after noticing that. 😛
I'd hope so heh
Nah you don't need System.Collections.Generic etc if you don't use those (List<T> etc)
This is fine, you have the Advertisements statement.
Is your IDE configured? If so, your code editor does recognize the interface.
I never know with VSC
Also not sure how "Restricted mode" affects things, might wanna disable that
#854851968446365696 has a guide with all the steps for VS Code
If you cant get it to work, switch to VS 2022 or something
hello
Then it's not configured, VSCode is a pain in the ass to setup, that's why I would advise against it.
is there an coding help channel?
Yeah, #💻┃code-beginner is probably a good place to start, reading the #854851968446365696 before asking questions is probably a good idea
I have no idea, don't think the ids by itself are harmful, but you can delete them for safety
Don't hand out the passwords though 😛
I mean you probably just need to put using UnityEngine.Advertisements; at the top of your file
The docs that were linked mention it and it's pretty obvious since everything has their namespace
He has that, we checked.
Then he has not properly loaded the dll
Yeah, his IDE wasn't setup. VS Code again..
So either the code he used isn't valid with the advertisement package he downloaded, or the dll isn't loaded.
is there anyone familiar with photon?
#archived-networking and just ask your question. dont need to ask if anyone is familiar
How do i make my code look more professional? I look at unitys code and it looks like something idk what, and mine still looks like the code i was writing when i started learning c#
By that i mean the layout of it all
You'll create your own style over time. The important thing is to be consistent with it.
So, you cannot set a block of pixels on texture2d.SetPixels without having a huge array filled with colors? What if I need only one color to be set for a block of 200x200? DO i have to fill a 40000 array with just color32.black?
this seems just plain stupid
Consistency is very important. Your code style should look the same across your scripts. If you place fields at the top of the class, all scripts should adhere to that. Also, read up on SOLID and DRY principles. They help integrate good patterns and teach how to avoid bad design in your code . . .
That's what SetPixel is for.
Why not make it 1x1 then? And just let it stretch out?
What if I need only one color to be set
you said you only needed to set one pixel.
Well, the example is weird, this is like saying a hammer is bad at cleaning a floor.
no wait
Oh sorry, you mean you want to set the same color to all pixels?
I need one color to be set on a block of pixels
this will need to be done a lot on blocks of 40 x 40, so i'm worried on performance
I really doubt i need to fill 1600 arrays with one color or iterate 1600 times to set a block of pixels to one color
I misunderstood, my bad.
no worries
(Though you should roughly adhere to C# coding conventions)
If you're looking for the most optimal method, I think a C# job and Burst will be fastest. With a parallel job, it will use all the available CPU cores and run optimized native code.
ah, well thanks
I will have to find a better solution then, because killing old android phones just for a pixel art canvas sounds excessive 😄
I still don't understand how there isn't a better solution to setting a block of pixels to one color
Repeating information is always bad. So I have no idea why you think you need 40x40 of the same information. Just stretch it out when you use that information somewhere.
I just don’t want my code to look amateur, even though i kind of am an amateur
That is, if these two red objects collide with each other, then the objects, i.e. the black boxes, will be perfectly connected. firstChild.transform.position = secondChild.transform.position + Vector3 offsetValue (HOW calculate?) (it is 2d game)
I need it to be drawn on users screen
Oh, quick question: I added Start and Restart methods, an OnRestart event, and suspended/resumed Timer when its host MonoBehaviour is disabled and enabled, but forgot which example you wanted added or explained to the Readme?
Read the Microsoft c# coding convention to see how style code guidelines . . .
So divide everything by 40, and all pieces are 1x1, and if you use that on a pixel perfect/no aniso/no compression texture it should still look the same.
Then you don't have to repeat anything and it's hundreds times faster.
That might work. Dont have a lot of experience with textures, thanks.
It will look amateur while you are an amateur, that's why you're an amateur. As I said, you'll develop a style over time, don't stress about it.
I’m not I just want my code to be neat and organized
and categorized, i probably want to categorize things too much
but to me categorized is organized
and it tells me what everything does and what it’s apart of
I think it was example of like using NewDuration();? Like starting a timer with an already defined instance, but I suppose Start(); would replace that now?
If you're only ever writing to this texture and never reading from it, then it would be faster to do it with a RenderTexture on the GPU. You won't be able to read pixels, because it will be stored in GPU memory, but writing will be much faster because the GPU is designed for that. Then you can do something like:
RenderTexture.active = yourRenderTexture;
GL.Viewport(new Rect(x, y, width, height));
GL.Clear(clearDepth: false, clearColor: true, backgroundColor: Color.black);
The GL.Viewport will constrain the clear operation to the rectangle you specify.
what is record used for? Usually you guys explanations are easier to understand then microsoft
also what does mutable mean?
A mutable object can be modified. An immutable object cannot be modified after it's created.
you can read pixels from rendertexture tho
Sure, I might have exaggerated. You can read it if you're willing to wait a few milliseconds. The data is not as readily available as a Texture2D stored in RAM.
ah ok
So what i thought static was and then realized wasn’t
the actual definition of static
yeah have to access them on PostRender far as i remember
but what about this?
record was added to make it easier to define classes that behave like immutable value types, which has more obvious benefits in more business oriented software development, like interacting with databases.
record is a class, but automatically generates boilerplate code you would otherwise have to write.
Ok, god so much of this stuff isn’t what it’s name would suggest
Thanks, got it . . .
I think in general it was just more examples of just using the instance without replacing the instance/without using all the static functions
(iirc)
what does this mean?
It means use () to make groupings of things explicit
oh wait i see
e.g. instead of a * b / c do a * (b / c) to make it clear
i didn’t read the example right
wait it would still work the same? i thought it would do a*b then / c
instead of b/c * a
sorry yes this will change it
yea
I'm tired
i was about to say oh shit my codes wrong
because i have something that needs to be divided and then multiplied by another number in that order and not divide the sum of the two multiplications
I've a basic form of Snake, where the body parts follow the player head position using a Vector 3 List of positions - however, as I pick up body parts, the distance between the body parts and the head seems to increase. Any idea why that might be happening?
Relevant code's probably in Fixed Update...
can you share in a paste site, cannot read the full file this way
When making an array of a custom class or struct, Unity makes this messy looking inspector. Is there any way around this other than making the array [NonReorderable] ? That works fine but obviously you lose the ability to reorder which is nice 😅
update your version of unity
this is a known bug in early 2021 LTS versions
Gotcha! Didn't know it was a bug. Do the more recent versions of 2021 LTS fix this?
yes
Ha of course. I've been on 2021.3.4 forever
Thought that was just something I had to deal with! I've been making all of my arrays non reorderable
was getting sick of it
i don't know dude. QA is a clusterfuck
Switched from Visual Scripting to proper C# after going on 2021.3.4 and haven't known anything different, just thought it was something I had to deal with lol
Hey, sorry about that: https://0bin.net/paste/aLLMKuX0#IzGH4hpcrJ8yWEbgvK-ZNvFi5Hu2m1vWC1xjwRZpRW6
0bin is a client-side-encrypted alternative pastebin. You can store code/text/images online for a set period of time and share with the world. Featuring burn after reading, history, clipboard.
Also, can anybody remember what the parent class for a TMPro text component is?
are you using Rider?
TMP_Text
ugh i wanted to teach this man to fish!!
oh sorry
lol
I'm using Visual Studio - help me fish! =)
i think Visual Studio has Show Hierarchy somewhere
But I appreciate the fast response from Praetor, I'm trying to get this done.
The script for Follower would be useful to see too
do you have Resharper?
0bin is a client-side-encrypted alternative pastebin. You can store code/text/images online for a set period of time and share with the world. Featuring burn after reading, history, clipboard.
Doctor, I don't know what that is. Is it fatal?
it's the jetbrains C# plugin for visual studio
it was big even in 2013
give it a try if you like VS
"Teach a man how to install VS Code, and he'll be stuck configuring for life"
I'll look into it. I don't really have a preference for an IDE, happy to take suggestions.
I've been coding on an unconfigured VSCode for the past week because it keeps unconfiguring itself and I can't be bothered anymore. Also I'm using a mac and VS for Mac is a trash pile too.
Slowly coming around to the idea of paying money for Rider
Either way, delighted to have TMP_text - I know you'd told me that before, Praetor, but I was wading through TMPro docs and trying to find that piece of info and going a little crazy.
Rider, c'est combien?
I'll look it up, thanks anyhoo.
i'm trying to write the bit where it's the scene in full metal jacket where hartman's yelling at the recruits their assignments and "Rider" is supposed to be "Infantry" but it's really hard
or is it that you finally configure VS Code and then shoot hartman?
i don't know
joker: "Are those... live prices?"
pyle: "seven six two euros... including VAT"
(pyle smiles grotesquely)
@leaden ice pretty nuanced
Not looking to rush you, @leaden ice , just checking - are you taking a look at those scripts, or can I check in on an friend?
I'm gonna phone a friend, will check back shortly--!
Hello,is there anyone know how to convert quaternion from ue4 to unity?(I want to use the characters in ue4 to control the characters in unity to do the same action,tried many ways,but failed)
Hey. Can you tell me please how i can get child object (Blue Key) with Box Collider in parent (Object) with Box Collider by Raycast? ( Two objects have Interactable layer ). Try get name child object by 'hitInfo.collider.transform.name' don't work. You have any idea?
GetComponentInChildren allows you to get components that are nested deeper.
But make sure to somehow use a layermask to make sure that you don't do that on everything. Like if you have a raycast-collision with a humanoid rig, GetComponentInChildren<Interactable> would search every bone that thing has.
but GetComponent in Update give bad performance when i will be see on parent object with 'Interactable' layer mask and if i will be have a few child objects in parent, i can't get child object which i need.
Okay "bad performance" yeah. In tutorials, people tell you to cache components that **can **be cached, like your playerControllers rigidBody where you use the same component every frame, it would be a waste of processing power to fetch that thing every frame.
In other cases like when you run around in game and you point at things and you want to check if they are interactive, theres no way to have cached that, you need to GetComponent<> on that object your raycast hits, like you already do. That's okay.
GetComponentsInChildren can be more expensive, especially if it is used on objects with a bigger hierachy where nothing is found, so the whole hierachy is searched. That's why i recommended to use a mask to make sure the ray only hits gameObjects that are okay to search.
Hi Im Working on Script That Reset Player Stats Every Monday is This Will Work ??
idk i like visual studio code
The code reset all data if the player logs in on Tuesday and if the last day played was not a monday, so no it doesn't. It will never reset if you don't play on Tuesdays.
I would calculate the days passed since last login and if thats more than the days since last monday, then reset.
Also you should format the date culture invariant and decode it via DateTime.TryParse.
#854851968446365696 for posting code
I didn't think thath I already use, but okay, my bad and I get it. But I still can't get the component I need from the child objects. Maybe I'm doing something wrong?
@devout solstice , whatever gets the job done, right? =)
Yea, i never configured visual studio code and it works fine for me
Just to illustrate the problem I'm having...
https://cdn.discordapp.com/attachments/85593628650504192/1063143413937098772/image.png
https://cdn.discordapp.com/attachments/85593628650504192/1063144371832233994/image.png
You can see in the second picture how the gap between the characters has increased as the convoy has become bigger and the movement speed has increased also.
does your ray hit the parent object correctly? Is the child component activated?
Yes. In first image my child object (key) inside parent object (this is not working), but when i taking out of the collider (just moving up, second image) is working and i get component from child.
I'm trying to get the text from an Input field but I get the "Object reference not set to an Instance of an object" error. What's wrong here?
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GetFieldInput : MonoBehaviour
{
void Update()
{
Debug.Log(gameObject.GetComponent<InputField>().text);
}
}```
How About Now ?
InputField component probably missing. Maybe its the TMPro input field type?
It is
Change InputField to the correct type
So this makes the snake go faster:
curSpeed = MoveSpeed + (Convoy.Count * SpdIncrease);
But PosHistory saved for fixed frame rate and Gap is also fixed, like "following the position of 10 frame before" so if speed increases the spacing would get bigger, correct?
Solved, thanks