#archived-code-general
1 messages · Page 211 of 1
A level itself cannot be an image so this doesnt really make sense
the visuals can, then have collision data as well
i was thinking arena game ish with seperated rooms
What do you plan to store inside the array? Like what do these ints represent?
You could probably optimize since I doubt every single element in your massive 2d array is needed
the ints are the pixel identity
like 0 is empty, 1 is layer 1, 2 is layer 2 (these dont rlly matter in terms of anything here, they just arbitrary)
ive used dictionaries for this kind of thing before, would that be a better approach maybe
also it seems performant rn for 600x400, it died when i tried 1366x768 though
does anyone know what's going on, this massage appear on my console, i just dont know what's wrong or what seem to be a problem, when ever i click anything on the editor it will appear that massage, but the game run normaly, any help for that?
seems that you need quad tree, but quad tree sucks if the image is too "fragmented".
1366*768*4=4196352bytes, 4MB
thats a scary amount of memory
it seems the main hit is the loop to tell my spriterenderers what colour to use, i guess that could be indivdual scripts job? or a shader somehow?
not a code question. and don't crosspost
i dont know where to ask
#💻┃unity-talk was fine
Hmm how many sprite renderers do you have? Honestly im still confused by the setup of this
cant you use tile map?
at least 1366*768 gameobjects, i believe your editor will crash (though loading 1M gameObject should be possible if your computer is powerful enough)
mhm
If anything you probably wouldve been better off generating an image based on the array and pasting that on a single object
It would be generated just once, your lag was probably just due to the amount of objects rather than anything pixel related
Either way yea tilemap is probably what you need
Yes, I've checked 😦
ok, I found the issue.
This is dumb, we have 2 different Animators that are both referenced by a parent C# class.
Therefore, the warning was on the other Animator. Sorry for the trouble. Thanks for your help
Hey there, I have this screenspace texture shader that works pretty much perfectly, except for one issue: the texture is too big. How do I downscale it? I can't seem to figure it out...
Here's the code:
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'
Shader "Unlit/Moon" {
Properties {
_Tint ("Tint", Color) = (0, 0, 0, 1)
_MainTex("Texture", 2D) = "white" {}
}
SubShader {
Tags { "RenderType"="Opaque" "Queue"="Geometry" }
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
sampler2D _MainTex;
float4 _MainTex_ST;
fixed4 _Tint;
struct appdata {
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f {
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
v2f vert(appdata v) {
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = ComputeScreenPos(o.vertex);
return o;
}
fixed4 frag(v2f i) : SV_TARGET {
fixed4 col = tex2D(_MainTex, i.uv);
col *= _Tint;
return col;
}
ENDCG
}
}
Fallback "VertexLit"
}
And here is a screenshot of what it looks like:
Fixed it! Just multiplying the uvs and setting the texture's wrap mode to repeat worked. Probably not the cleanest way though.
that should be the cleanest way
I mean you could modulus the UVs to make them repeat yourself but your solution is the how its almost always done
General more theoretical and functionality question here
I am making a game with multi dimensions that can be switched inbetween
Should this be handeled in one large script that alters between them with button pressing on an empty game object
Or should this script handle bools that communicate with seperate scripts to handle these realms
Well, what exactly does it mean to switch between dimensions from the technical point of view?@fiery path
idk, there is not enough info to help here
Let’s say I have a list to iterate through, and a tree class that contains some of the entries (tree is subset of list). The logic for the order goes by:
- yield return all entries where field1 == 1, and not in tree, sorted by GenericSortMethod.
- enumerate through entries of tree, which has its own logic,
- yield return all entries remaining, in order of GenericSortMethod
is there a way to do this without just making a bunch of lists and concatenating them? I’d theoretically want to just get an IEnumerable
Tree currently can output an IEnumerable for its own order
Also, I am okay with modifying the order of my list
Think of it in this sense
3 states (simplifying this mega lets say switching between three auras)
i think i understand the problem statement, so you have a tree and you want to iterate the elements stored in tree node in a some order without pushing every element to list and sort it....
yeah, tree sorts itself, and uses its own recursive methods to give an IEnumerable for itself
Pseudocode would look something like this:
public IEnumerable<T> IterateList()
{
// 1. sort the list.
GenericSortMethod(list);
// 2. return filtered entries
foreach (var entry in list)
{
if (entry.field1 == 1)
yield return entry;
}
// 3. enumerate through tree
foreach (var treeEntry in tree)
{
yield return treeEntry
}
// 4. return remaining entries
foreach (var entry in list)
{
if (entry.field1 != 1)
yield return entry;
}
}
The multiple enumeration of list can be avoided by filling an intermediate list during the first iteration, but that uses more memory and allocates garbage if you don't pool it.
so is the order of tree different from the order you need in this iteration? if yes then i think you must stores the entries in list then sort it....
Ah, forgot about the "not in tree" condition for the first step.
yeah, three enumerations + full sort might be the way to go. Not sure if there is a smarter way
tree ordering has its own rules
guys can you help me
similar, but obeys tree structure
how do i check for collisions in an if statement
tree can be unordered but no one will use it
assume tree manages sorting itself
before we start, it is ready to spit out an Ienumerable
tree has a dictionary, so I can easily do tree.Contains without difficulty
if the order of iteration is different from tree, that means you have no way to predict where is the first element, second element and so on, then list is needed in this case
you don’t. You normally get collision callbacks via OnCollisionEnter etc. During that callback, you can set/store bools to use different if statements on
maybe your tree is sorted by field0 but you need to iterate in the order of field1 etc
so how would i store a booelans?
i am kinda new to unity and c#
just came back after 3 years
correct. I don’t know. but I also don’t NEED to store everything in a whole list separately.
private bool hitSomething = false;
yeah
you can handle things during collision callback, which happens after physics step. Or you can store information to run things at some other time
hello
Maybe I should make a different tree structure, that consilidates everything via root nodes
This is not very detailed. Or technical.
I was thinking about state machine, but since it's only 3 states, it might be simpler to just hardcode it.
Now, whether to put it all in one class or multiple, depends on many factors. If you can isolate separate objects/behaviours without spaghetti dependencies between them, it's a good idea to split it into several classes. Can't say anything more specific without more details on your implementation.
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
😮
https://www.reddit.com/r/gamedesign/comments/179c7o9/multidimensional_scifi_shooter_feedback_discussion/
This was my overall idea
I can look into sate machines tho and how they work especially since I may expand past 3 realms
your problem can be translated to:
how to iterate a unordered list (since tree can be iterated as list with dfs and the order is different from tree, can be treated as unordered) using constant memory (stack needed in dfs is ignored) ofc O(n^2) time O(1) memory exists.....
So it's sort of like area of effect abilities or "modes". State machine might work pretty well for that purpose.
Yeah exactly
aweomse ill have a look into them
thank you
Hey, I have a list of layers
[SerializeField] private List<LayerMask> _playerLayers = new();
and im trying to change layer of a player when he spawns
player.gameObject.layer = LayerMask.NameToLayer(_playerLayers[_playerCount - 1].ToString());
but i get this error
A game object can only be in one layer. The layer needs to be in the range [0...31]
Why?
also, refactoring my tree to not autodelete nodes with no children, and using a treenode class helps so much.
layermask is not layer
so what should i use
it’s a bit confusing. LayerMask is an enum flag type
look at your code
List<LayerMask> _playerLayers
...
NameToLayer(_playerLayers
what do you think?
layer is an int, which corresponds to one of those bits
i always forget, so I use a package with a static Layers class. So I can do things like Layers.ENEMY and Layers.ENEMY_MASK
it greatly improved my workflow with layers
whats the name of this package?
Guys, good day :3
Sorry for the stupid question, I'm a newbie game developer ❤️
What's the best way to design level changes for indie platformers? is there any guide? Is it better to do this on one stage or create several for each level?
#archived-game-design is probably able to link you some resources. This channel is for code questions.
no clue
LayerMask is an int, you are trying to get the Layer name from it, that ain't gonna work
I use this one: https://openupm.com/packages/net.tnrd.layertagsgenerator/
there are many options. I like this one because it just generates static classes with public const int
no references like other packages. just const
my professors in college told me: consts basically tell the compiler to control+F modify your code before compiling it.
depends on language, but true in c#
this was in context of C and C++. Not sure how big C# was during my college years
Python and C++ were the big players at the time.
I have another issue
i have a sprite with box collider (trigger)
private List<Collider2D> colliders = new();
private void OnTriggerStay2D(Collider2D other)
{
if (!colliders.Contains(other) && other.transform.CompareTag("Player"))
{
MainMenuManager.Instance.PlayersInsideStartingArea++;
colliders.Add(other);
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.transform.CompareTag("Player"))
{
MainMenuManager.Instance.PlayersInsideStartingArea--;
colliders.Remove(other);
}
}
PlayersInsideStartingArea = 1 when player enters this sprite
but it increases to 2 when he jumps
any ideas why?
no, maybe try log if (and why) the increment is executed twice
and consider ontriggerenter, though guard is still needed
void OnTriggerEnter(Collider other){
debug.log($"other is {other.go.name} tag is {other.tag} is the list contains it {list.contains(other)}");
}
log all infos you need
for some reason it fails at Contains
fixed
i changed the list to the list of GameObjects
exactly how do IEnumerable/IEnumerator work with foreach enumeration? The syntax always confuses me
just cpp iterator* it=something.begin();it!=something.end();it++, but the ++ is overloaded...
Hello, can anybody tell me (maybe a link to documentation) what API should I use if I want, from Script, to add an actual Prefab instead of instantiating an instance of it to my GameObject please?
I want version 1 and not 2 of my screenshot
I see. So from a functional standpoint, IEnumerable allows clean foreach syntax, while IEnumerator has messier syntax (because you need to cast), but allows you to manually iterate/skip/reset if needed?
Can someone tell me how to fix this please I’ve suffered for 3 days trying to start making games
I'd say it's more both work in pair.
IEnumerable return an IEnumerator, and each Enumerator is able to give you the next one. But yes you can have IEnumerator alone and do the heavy lifting yourself
This will return an instantiated clone (version 2 of my screenshot).
Ha, it says somewhere PrefabUtility.InstantiatePrefab
Thanks 🙂
i don’t understand. Instantiating a prefab makes a clone
it’s a prefab. that’s the point
reset a iterator is equivalent to create a new iterator, i think foreach is just syntax sugar of getting iterator->while(haveNext())->moveNext(), you can still continue; and break; in foreach loop
Yes, but I want to keep working with the whole linking to parent Prefab etc
It's editor behavior, not runtime behavior
oh. that’s really weird. you usually don’t want to do that
nobody 😭
To be clear. A prefab is a file. It's a blueprint. You are saying you want to modify the blueprint?
If it's in the scene, it is an instance, not a prefab
It's QoL.
If a script is added, I want to automatically (in Reset() function) add a Prefab as a Child.
Yes yes, I'm clear on the distinction, thank you for your help
oic. that is a weird use case
ask it in unity-talk
you know you can have a prefab in a prefab too, right?
like, I have UraniumBlock as a prefab variant of a generic solid prefab, and it has a RadiationField child object which is linked to a RadiationFieldPrefab
Well to give a bit of context:
I have Interactable script on Interactable gameobjects. I want to add a World Space Canvas feedback above each one. For now, I can't really have a parent prefab (in the future, I will have a single prefab where all interactable objects are Variant of it, so no problem), but for now, I want some QoL to improve older scenes.
So my approach was to add some behavior in Reset() function of that script so that it adds what it needs when it's added, but I don't want to just add a cloned object, I want to keep the whole "working with prefab" thing
I'm quite well versed in Prefab, yes, I know about nested and variants. It's a temporary QoL, not a best case scenario sadly
But I appreciate the feedback 🙂
just making sure you aren’t making life harder than it needs to be
Yes for sure, it's appreciated
Using PrefabUtility.InstantiatePrefab worked like a charm.
sounds good
How does one properly setup URP shadow distance as a option? I'm looking at this and its not sticking. https://forum.unity.com/threads/change-max-shadow-distance-at-runtime.1325874/
why when i print jsonOverrides it prints : "{}" while print(overrides[key]) prints : /e
(i need jsonOverrides to store the changed key but i have no idea why it does not work)
code :
private void SaveOverrides()
{
//save
var overrides = new Dictionary<System.Guid, string>();
foreach (var map in actions.actionMaps)
{
foreach (var binding in map.bindings)
{
if (!string.IsNullOrEmpty(binding.overridePath))
{
print("saved");
print(binding.overridePath);
overrides[binding.id] = binding.overridePath;
print(overrides[binding.id]);
}
}
}
print(overrides.Keys.Count);
print(overrides.Values.Count);
print(overrides.Count);
string jsonOverrides = "";
foreach (var key in overrides.Keys)
{
print(key);
print(overrides[key]);
jsonOverrides += JsonUtility.ToJson(overrides[key].ToString());
print(jsonOverrides);
}
print(jsonOverrides);
}
how do you have any idea which print statement is printing what? You're just calling print with no context. That will make it very hard to tell which line of code produced which log
You should add more descriptive text, for example:
print($"Full jsonOverrides string: {jsonOverrides}");```
the order in which it prints
sketchy - anyway show the output
(exemple :
yeah i can't make heads or tails of that
ok so
add more info to the logs
also you have Collapse turned on as far as I can tell
which is going to really confuse the ordering
would have to show the corresponding code
private void SaveOverrides()
{
//save
var overrides = new Dictionary<System.Guid, string>();
foreach (var map in actions.actionMaps)
{
foreach (var binding in map.bindings)
{
if (!string.IsNullOrEmpty(binding.overridePath))
{
//print(binding.overridePath);
overrides[binding.id] = binding.overridePath;
//print(overrides[binding.id]);
}
}
}
string jsonOverrides = "";
foreach (var key in overrides.Keys)
{
print($"overrides key string: {key}");
print($"overrides value string: {overrides[key]}");
jsonOverrides += JsonUtility.ToJson(overrides[key].ToString());
print($"Full jsonOverrides string: {jsonOverrides}");
}
print($"Full jsonOverrides string: {jsonOverrides}");
}
This: JsonUtility.ToJson(overrides[key].ToString()); makes very little sense
why are you calling ToJson on a string?
to put it to json format right? and the store it in a file
that doesn't make any sense, no
you don't put strings in json format
json IS a string
you take objects and put them in json format
oh well i'm dumb
in any case you don't need to do any of this yourself
SaveBindingOverridesAsJson creates the JSON string for you
unless you're not using the input system?
thanks you 😅 and sorry for waisting tour time
i am but i'm using the 1.0.2 so it ain't in yet or at least it didn't work when i tried
are IEnumerables generally lightweight to work with when I don’t need to save the whole thing to a list?
can't you upgrade?
IEnumerable is an interface
List is an IEnumerable
having an IEnumerable reference doesn't actually tell us the nature of the object
for some reason i can't
what version of Unity are you on?
2021.1.1.5f1
started the project on it and did not upgrade
i understand, but let’s say that I store a List<T1>, and I want to mostly just enumerate based on and outputting fields in T1. Is making functions that give IEnumerable<T2> etc a more lightweight way to do this?
You should upgrade to 2021.3 LTS
Then you'll be able to get newer versions of the input system package, among other things
will some code be broken by updating (just to have an idea)
shouldn't be but as general practice ALWAYS make a backup and/or commit to version control before upgrading
like, if T1 is a monobehaviour, and I want to iterate through the GameObjects, and don’t necessarily need to save a whole new list of GameObjects. Would making a method that returns IEnumerable<GameObject> be smart or no?
There's nothing more lightweight about it. If the underlying object is a list, it's still a list even if you pass it around as IEnumerable.
ye i'm doing it right now :`D (would you be bothered if i mp you if i encounter an issue while upgrading?)
I mean yes it's smart in the sense that callers won't be able to modify your list. But IReadOnlyList is actually probably better than IEnumerable
i’m thinking more about avoiding making a whole new second list (temporarily) for enumeration
which avoids allocation/GC
yes, but in that sense there's little difference between passing the existing list around directly as a List<GameObject> and passing it around as an IEnumerable<GameObject>
they are both just different views to the same object
I do think it's a good idea to pass the list around as IReadOnlyList<GameObject> if you don't want scripts that receive the reference to tbe able to modify the list
i.e.
private List<GameObject> myList = new();
public IReadOnlyList<GameObject> PublicListRef => myList;```
i was basically refactoring the Tree to use TreeNodes, and wanted TreeNode to just be internal to tree, while tree doesn’t expose that class at all
In that case You should/could make a public interface
which determines the exact API surface you want to expose to the outside world
and expose your objects as that interface instead of the actual class
||/// <summary> Don't modify this! Use XYZ methods. </summary>||
Why is my gun pointing at my player and is so far away? (it rotates with the camera)
On the first pic u can see, it is right next to the player but when i start the game the gun is far away (pic2)
without any details such as the hierarchy setup, the components that are on the objects, the code, etc, nobody knows.
If I want to make a 2d platformer using visual scripting, would I be limited in some way?
Visual scripting is somewhat limiting, sure.
It's harder to express many things in Visual Scripting
but aside from those usual limitations, no.
yeah my bad. I send a video
@old haven sure you wanted to tag me buddy?
lol my bad again
ive sent a video
Ty. Right now, they are actually generics, with Tree<T> and TreeNode<T>, with TreeNode<T> internal, and Tree<T> has accessors to probe TreeNode<T>’s contents.
the gun itself has a networktransform and a script on it
one or both of those may be messing with its position
u mean those? if yes, i turned both or one of them off. and nothing worked
you'd have to also show what's inside the AK47 prefab
nothing "fancy"
looks really fancy to me
but yeah would need to know the components on all these
is there a Rigidbody for example
there is nothing just mesh filter and mesh renderer. on the "Bulletspawnpoint" just Transform
It's very likely that your model's pivotpoint is broken. With that many child components that might be the reason of your problem
that too ^ I notice tool handle position in the video is set to "Center". Press Z to toggle it to "Pivot" to see the real object pivots
Is the gizmo on top of your model when you choose it or somewhere else
this thing
Your PlayerNetwork script may also be at fault
it seems to reference the weapon xform so could be doing all kinds of things to it
@leaden icewhat was the side again where u can send the code?
also pivot doesnt work
can i put all in one?
You can use gdl.space or hastebin.com
wdym by "pivot doesn't work"
as for code: !code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
@leaden icehttps://gdl.space/irobabaxil.cs Playernetwork
and https://gdl.space/kahopehipo.cs Weaponcontroller
weaponTransform.position = kameraTransform.position;
// Aktualisiere die Rotation der Waffe
weaponTransform.rotation = kameraTransform.rotation;```
this looks pretty damning
this combined with the above mentioned likely issues you have with your object's pivot explains the issue
should i delete it?
delete what
the code?
No you should fix your pivot issues
although really why not just make the weapon a child of the camera instead of having that code.
lol this worked thanks
This definitely points to it being a pivot issue then FYI 😉
your mesh's origin and orientation are way off as imported currently
Switching from Center to Pivot as described above will show you where your weapon's actual pivot is.
so i'm having an odd issue with RaycastHit.point, it's working perfectly along the ground plane, but when hitting an object it's returning the correct position but with the y value always 0
show code and the scene/raycast setup?
Presumbly the hit point is correct.
nevermind, rebooted unity while i was typing that message and now it works correctly
🤷♂️
"ruins everything" is hyperbole
handling errors in your code is a skill that you learn over time, and it's normal and not a big deal to have and fix errors as you grow more experienced.
https://www.youtube.com/watch?v=MyuZC40vNr4
anyone who knows perlin noise / unity can you please check this vid if the code is correct?
similar to diamodn square algorithm
In this video, we will create a perlin noise procedural terrain, using the Unity Mathf.PerlinNoise function.
In this video, we will look at how to go at creating a procedural terrain using the Diamond-Square algorithm.
Custom Mesh video: https://youtu.be/UeqBwK27sV4
did you really have the need to obnoxiously crosspost this ?
i mean people answering in beginner and here
are different
var deathEffectParticle = Instantiate(_playerDeathEffect, player.transform.position, Quaternion.identity).GetComponent<ParticleSystem>();
var color = PlayersAndPoints[player].PlayerColor;
deathEffectParticle.startColor = color;
deathEffectParticle.Play();
then pick a channel and stick with it. No need to cross-post
NullReferenceException: Do not create your own module instances, get them from a ParticleSystem instance
im getting this error
why?
alright
why not just make _playerDeathEffect a particle system type
then spawn it as ParticleSystem
another question how to check memory usage of the loaded maps? Because i am doing a study about the memoery usage of these two algorithms with respect to independent variables: terrain size and fps
use the memory profiler?
very dumb question but I would like to edit animation keyframes in playable director however when I ijmported my animation from blender they're all grayed out and locked does anyone kno whow to unlock them
This is an #🔀┃art-asset-workflow question but - duplicate the animation clip
and modify the duplicate
ok ok thank you i'll refer to #🔀┃art-asset-workflow if I still run into problems
how
sorry i dont know
i only know this
ama check google
Hello everybody,
I'm a relatively experienced developer with a bunch of engines, but not so much with the 2D part of Unity.
I am working on a simple 2D platformer with a mixture of 2D and 3D graphics. Unity seems a good fit for that.
I started working on a 2D character controller and faced issues almost immediately. There is no alternatives to the CharacterController for 2D. So I had to make a choice between using a dynamic RigidBody, a KinematicRigidbody or shape casting.
The game I am making is quite arcady and I want full control. I chose against a Dynamic Rigid body.
I chose to go with RigidBody2D.Cast because I thought it will work with the rest of Unity. I guess I am wrong.
The controller itself was easy to implement. But I can't seem to make triggers work with it.
At first they were blocking the body. I found a way to go around it with a contact filter. But now entering a trigger is simply not detected.
I found a few solutions online but they are either hacky or really inefficient (overlap in the FixedUpdate).
Is there a better way to do that? Also, if rigidbody.cast does not work with triggers are there any benefits over a shape cast besides being able to use multiple colliders per object?
is there a performance difference between raycasting 100 units and raycasting math.infinity units if the object it's hitting is the same distance away?
probably not a noticeable one but 
I would be more worried about correctness here than performance.
hey yall im trying to follow this tutorial but im a bit confused on one of the steps
In this video we're going to take a look at Camera Stacking with the Universal Render Pipeline, in short URP, using Unity! Using Camera Stacking you can layer game UI in Unity very quickly, and author high quality user experience.
Download the Cockpit demo, along with other URP example projects here!
https://on.unity.com/3jUFeQm
More info on...
specifically when they begin making the overlay camera
is the game object they use to put the camera in like completely empty? how does it render the cockpit then?
because its set to only render that specific layer
is the whole cockpit on a specific "cockpit" layer then?
like the base structure bottom left right screen top thing
yes
the cockpit object is set to cockpit layer and on cameras you can choose specific layer to hide (cull)
so you hide it on main renderer cam and show it on a separate cam
this is useful for many use cases
ty
no one has an answer?
I just don't think people are going to commit to watching a video to answer a question here >_>
this should go in #💻┃unity-talk btw
code questions , yes
i seee
Hey there! Is there a place where i can find simple scripts like a car control script ?
No, we usually help with existing code. Code generated with AI does not count
If you need someone to write code for you, then you need to post a job offer on the Forums
the internet is literally full of them..
uh... okay
I want to create a multi windowed game, such that one window shows the game, so that it can be streamed or whatever, and the other window shows the options/actions that interacts with the game. Is this possible to do in Unity?
ofc
eg
oh wait you mean two separate monitors
in that case use this option TargetDisplay
if you mean two separate executables thats tricky but doable
Unity has multiple display support, just Google it and read the documentation
yeah i mean like two separate application windows, kind of like maplestory external chat, where they can be moved around separately
Separate application windows may require some native windows plugin shenanigans
Maybe you could use some networking solution then just have both games communicate locally
launch it twice then select which one is your main game and which is your external options/actions
Hey, can I somehow make player not affected by Global Volume Bloom?
I want only specific parts of the map to glow and not the player
afaik the most you can do is exclude specific layers from all PP on the cam, not sure about a specific effect is possible
also not a code question
like this?
cuz it doesn't seem to work
i'm not sure , you can try ask #💥┃post-processing
oke
https://hastebin.com/share/eqalujenac.java
i am at a literal loss to why the fk its out of bound
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i am literally following a tutorial too
okay, i'm a bit confused 😄 I try to instantiate ui objects inside a scrollview content and set their position as needed. They are instantiated correctly, but somehow the position is absolutely not correct. The printed values are correct, but they dont match the rect transform position inside the content object.
leadPrefab.transform.localScale = Vector3.one;
leadPrefab.transform.localPosition = new Vector3(-30, 300 - i * 210, 0);
Debug.Log(leadPrefab.transform.localPosition);``` prints : -30, 300,0. Actually is -570,1000,0 (shown in editor.)
something wrong in this for sure int mid = (int)(row + halfSize)*(mDivisions+1)+(int)(col+halfSize);
Log the value, as well as the length of the collection you're trying to index with that
why log
The most confusing shit is that it actually changes the position correctly by 210 units when instantiating more that one object. But it is not from 300, but from 990 lol. The audacity
debug.log, not math log
So you see the value of that monstrosity of a line
lol
i forgot debug log exists
i didnt code for a while
Rect Transform shows the .anchoredPosition in the Inspector. You need to cast your transform to be able to access it.
ahh
okay
thanks dude, it works
completely forgot about the differences from rect transform and transform
there is 25 vertexes so the mVerts = new Vector3[mVertCount]; Has array size 25 so when we did mVerts[mid] which is 16 within the bounds
then wtf i am getitng out of bound error
code ehre
i just checked the count in this iteration, vector3 array didnt change its length at all
hello guys, i need some help please.
i'm facing the following problem: i have those mixer groups, all the parameters are exposed. I have some snapshots with different audio values. I change the Music value in the game though the slider, but when I do this and the value is changed, it prevents the Music channel from being controlled by changing snapshots. The other values changes without problem but Music is the only disobedient one.
The formula in the code keeps the volume between -80dB and 20dB
after 1hr and half of hell...it was me putting the wrong value in the for loop condition
it happens a lot with me lol
this shit looks awful
i did the code correct but was there a change to random.generator by any chance
i suspect the issue is with random geenrator
i rly need help fr
https://hastebin.com/share/eriyivavag.java
this is the code
The terrain shouldnt get like that at all
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
what is the best way and easy way to make online game in the way players host it self like pair to pair ?
Sorry to tell you but the error is most likely your code, implementations dont just change like that
it should be smooth like this
i am sure its correct
bec i understood the code perfectly
from youtube
i reviewed many times
In this video, we will look at how to go at creating a procedural terrain using the Diamond-Square algorithm.
Custom Mesh video: https://youtu.be/UeqBwK27sV4
Looks like you most likely have the vertecies switched
from what your screenshots look like
in the tri order
ok i will check
i just checked
doesnt seem to wrong
its 3am this thing still not done🥲 cant figure out the mistake
@dusky lake i am not figuring out how
Either step through the code or print the first few vertices and their intermediate calculations.
i did for smaller values, its look right
debug.log the value of verticies?
Yes
can you, just for a test, crank up the division count?
I don't know. You tell me. How is it supposed to look?
From what I've seen in the previous screenshot, it's the vertices positions that are wrong, so turning of shadows just hides the issue.
true
the height divison yeh?
it can be maximum of 128 , each of the mini square is considered mdivisions
I'm trying to paste code, but it seems to have an asterisk that I've never seen in C# before, and it's causing errors. Hoping someone could explain what this is about.
the asterisk is wrong here
it's possible they wanted to do samples * i though
in which case it's just the multiplcation operator
@cosmic rain @dusky lake i followed this tutorial for the past 8hrs(8hrs bec i was trying to understand)
i read thru everything checked etc... the code is correct
Ah, hopefully. This was the code I'm trying to implement. Both of the examples in the thread seem to have formatting issues lol
you'd have to show what you're talking about
https://hatebin.com/jvhgjmbjrp @cosmic rain
definitely just some formatting issue
I think it's just supposed to be Mathf.Abs(samples)
Well, if it produces an unexpected result, it's not. Step through the code when it produces the wrong value to see what's going wrong.
Mathf.Abs(samples) produces an error 'cannot convert from float[] to float'
i ahve been stepping through it for past hour , ig i will just sleep
you'd have to show the full line of code
You only need to step through it less than 10 min
did you do waveform = Mathf.Abs(samples);? Why did you delete the subscript on the left side?
Didn't you say it's more likely the movement?
i was trying to implement the edits mentioned later in the thread. i can try to do it the way the first poster suggested
you dont want to see that
ever seen spaghetti
I don't. But then what's the point of sharing an irrelevant script?
again you deleted the subscript on the right side, why?
you had it correct here
maybe that you'd immediately see something thats wrong i can send the movement
hatebin cannot handle my script it simply wont load
Subscript? Sorry, I am trying a lot of changes but they all result in error
It's a bit tricky because the thread suggests two methods. My original image was based on the second one
waveform[s]
i mean you can understand what the error is saying right?
And why the code without that makes no sense, right?
https://paste.ofcode.org/32wsCk535VTaeciWeqNPE4N i think this website works
waveform is an array
Still an error
samples is an array
This is a very weird camera controller. Disregarding the Find in update, which is a horrible idea, the fact that you set the rotation of the camera separately from the player doesn't make sense. Also, rotating the player in the camera script doesn't make sense either.
Try disabling this script and just parenting the camera to the character.
Also, maybe just follow a fps controller tutorial...
Yeah, I mean this is square one of why I was confused in the first place
they had samples*
yeah the formatting on that site is clearly very fucked
yeah maybe samples[i]
fps controller tutorials are too simple made i am building something more advanced and thats when i ran into this large issue. i've followed many tutorials in the past haha
at this point i'm taking shots in the dark lol but thanks for trying to make sense of this
ill try disabling the script
I'm pretty sure [i] was like bbcode for italics
which destroyed the formatting
Get something more simple working first. It kind feels like it's too early for you to build something more advanced.
ahhh
Besides, you can build on an existing controller to make something more advanced. At least it would have the basic mechanics implemented properly.
ive disabled the movement script and it still does it
Movement or camera?
movement
Disable the camera script as I suggested
Didn't you say that it was still happening after disabling the movement?
shit
Disable both for a test
i will but then i cannot do anything
But then it would probably confirm that it's one or both of these scripts.
In which case, as I said, go implement a basic controller first following a tutorial.
i have a short feeling its not the scripts
What then?
ive disabled all scripts and i try to move my player trough the world and its glitching like that too
How are you moving it?
just in the scene view
Via the transform gizmos?
What other script do you have on or that reference the player/camera?
yes transform gizmos
lil axis
let me check because im unaware of any other scripts then these
Is it not your project?
it is mine but i cannot remember putting anything on anything else
i have one more script on my feet transform but i doubt thats it
thats all on this one
What's BaseMovement? Is it the movement script that you disabled?
yes thats the movementscript
this code doesn't make sense
This is saying "when I collide with an object that is NOT the ground, make grounded false"
What you actually want is "when I leave the ground, make grounded false"
Okay. Take a screenshot of your character inspector and the whole editor window. As well as of your camera inspector with the whole editor window.@scarlet juniper
this is the player
so just the whole screen
Yes.
Also, I can already tell you that rigidbody and CC combo is not a good idea. I'm not sure if it's the source of the issue, but it could be.
No good. This is why your camera (and everything else) is misbehaving.
what am i missing
.
Also the PlayerCamera object too.
The rigidbody and the character controller are going to be fighting over how to position the player
You must not use both.
ive deleted the cc and its still misbehaving in the scene view
this is whats going on rn
Also share:
#archived-code-general message
Try removing the CC entirely.
its empty
still doing the weird
i feel like im just annoying atp
Hmmm
a second one? or just enable the first one
its a trigger
so its not colliding with the main
it was for the old script that didnt make sense
Disable that trigger and add a normal capsule collider to the rb.
But that is the transform you're moving in the video
I wouldn't expect dragging a rigidbody around to make you "lose your grip" like that
Wdym? You don't have any on the character from looking at the video.
there is yes
although, it's also a trigger
its a trigger yes cuz that one was going crazy with the collider from the CC
the transform is the player as you can see thats what ive selected in the vid
enabling and making it non trigger dont work either
Does it do the same thing as in the video?
yes same thing]
Did you disable/remove the box collider/trigger?
Is the problem that the object is only being moved for one frame in the editor, and then you "lose your grip" on it?
If so: create a cube, add a rigidbody, and see how it behaves.
What are Body and Cube doing?
Are there any scripts there?
Deactivate children until the behavior changes.
Also, are there any OnCollision/TriggerEnter/Stay/Exit in any of your scripts on the character?
Because these would run even if the script is disabled.
ive disabled everything but the cilinder and the camera and now it works smooth
i am so lost
Well, then start re-activating things.
This would be my guess.
I don't see it on the screenshots
Also, if it could just disabled the symptoms of the issue
You still have a bunch of components that could be receiving physics messages
notably, your framerate is going from under 50 to over 50 when you turn off that volume component
Perhaps you have code that malfunctions if two physics updates happen between two frames
It shouldn't be. I'm inclined to think what Fen mentioned.
Unless it's some kind of editor quirk. Still very unlikely.
this is getting way to advanced now for me
One thing that bothers me is that the capsule collider seems to be shivering a little bit...🤔
That is very abnormal, yes
If you won't read through your own code, you can at least start removing components and seeing if the behavior changes
Repeatedly declaring that you don't understand isn't going to get you any closer to understanding the problem.
It's weird, yes
You can share those scripts you have attached to the player, perhaps.
That's what happens when you want everything at once, but not ready for it. Referring to trying your own "advanced" controller implementation+ using hdrp.
i understood the statement wrong i thought i had to go into unity's code
you do not, no
Try removing all the scripts from your character controller(could maybe duplicate the root object to preserve them), and see if the issue occurs.
there is not 1 script in the entire scene anymore and it still doesnt
everything is deleted no more scripts
its also 3:37 so my brain aint braining anymore too
Look at it later
trying to diagnose a weird problem at 3:30 AM is a terrible idea
there's going to be something niche happening here
i have one more option. im draggin the entire world in there WO any colliders on the environment
if that dont work im gonna sleep
nope it dont work, welp ill get back to it tomorrow, if anyone is willing to help me
thanks for all the effort
Most likely, the transform gizmos not moving it is unrelated to your original issue. This must be some issue with how unity syncs transform and physics in the editor during low frame rate.
yes im not too bothered by that but i am bothered with that awfull main issue
we'll see tomorrow, cyall and thanks again!
if an object is being rotated via a drag script is there a way to tell if it is spinning clockwise or counter clockwise? I figured I could take the Quaternion rotation of the previous frame/drag tick and compare it to the current one but haven't really found a way that returns a value that clearly tells if rotating one way or the other
It would be easier to check the drag values instead of the rotated object
"via a drag script" is very vague
should be very easy if you have access to the script
exactly - the script knows which way it's turning the object
Like, get the direction vector of the initial drag start point and the first OnDrag() point and base it off of that?
no, like the rotation script already knows this stuff
yep sounds about right
if it's doing the rotation
it's hard to not be vague without seeing the existing code
The rotation is happening with Quaternion.AngleAxis()
that's how a quaternion is being created. the parameters to that AngleAxis call come from before it
I think thats what he means, using the drag values from the drag script 😄
I'll give this a try, I feel like I tried it before but I must messed it up. Think it should be as simple as checking if the x value is going positive or negative on that first drag
dont look for the first drag, minimal movement could trigger a false trigger
give it a threshold of some units
Basically if the angle you're passing in is positive it's clockwise
Else counterclockwise
Simple
Not really that simple because rotations are a nightmare. Where
Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
post = Input.mousePosition - pos;
rotationAngle = Mathf.Atan2(pos.y, pos.x) * MathfRad2Deg;
transform.rotation = Quaternion.AngleAxis(rotatingAngle, Vector3.forward);
Rotation angle will veer into both positive and negative values regardless of which direction you spin so it hasnt been a reliable way to tell which direction we're rotating the object
So I think I'll stick with looking at drag directions if possible
See this is why we needed to see the code
it was very unclear how the drag rotation was working before
so hard to give a good answer
I was under the impression it was something like dragging left/right and doing additive rotations
which is not the case
Anyway I'd just use https://docs.unity3d.com/ScriptReference/Mathf.DeltaAngle.html
float diff = Mathf.DeltaAngle(previousAngle, currentAngle)
check if that's positive or negative
After trying many, MANY types of rotations, using AngleAxis was was the best way to rotate smoothly without awkward jumps when it reached 180 degree range and dealing with the previous rotation. eulerAngles were a hard no go
AngleAxis is not the question
it was about whether you were additively rotating or setting the rotation
This should be a good solution for you
How does the method handle negative values? Because for example, when going counter clockwise based on the axis the angle should be increasing but at 180, the next agle will be -179. It will increase from there from [-179,0] but will it account for that one gap where values don't increase?
it handles them just fine
read the doc
if you do DeltaAngle(180, -179) it will return 1
Did it say that on the doc? Guess I missed it?
Calculates the shortest difference between two given angles given in degrees
the shortest distance between 180 and -179 is 1
And then the doc proceeds to give an example with two positive values so that's kind of an assumption to make. "read the doc" given the example is pretty condescending lol
i do believe you
Can someone help me understand this?
private bool IsIdentifierStartChar(char c)
{
if (char.IsLetter(c))
return true;
if (c == '_' || c == '$')
return true;
return false;
}
Will this not always return true, since the if statement is referencing the char being passed to the method?
why would it? What if you passed '#'
Would the very first if statement not basically then say if(char.IsLetter('#')...in which case it would return true, since that's what you passed it.
"#" is not a letter though
Okay. So I misunderstood the usage of IsLetter() apparently then. It's checking to see if the character IS A LETTER... It's not a comparative method.
My mistake.
If the word start at _ $ or letter then it maybe a valid identifier
If the goal of the first if-statement is to basically see "is the character provided the letter c specifically", you can use .Equals, which will compare two objects, so for example var x = 'c'; bool isC = x.Equals('c'); "isC" will be true if indeed the variable x happens to have the value 'c', otherwise itll be false
Btw you can just
return char.IsLetter(c)||c==‘_’||c==‘$’
hey Ive asked #archived-lighting but does anyone know here know of reflection probes ive been stuck on a small detail with them
Hey developers. I'm coming to unity from Unreal. I have a value I want to be able to set from anywhere and have it persist between scenes, but not a static method because I want to be able to edit it at editor time. For Unreal that would be a value in the GameInstance. What about for unity?
From what I can tell I would want a gameobject that's marked Don't Destroy On Load, but I would need to ensure one exists on every level in my project?
Perhaps you are looking for DontDestroyOnLoad. Idk unreal stuff but this would have an object persist across scenes. Then data can live on that object
@lean sail How do you ensure the object would be present in every level and avoid duplicates or absences?
It could depend on what this is actually used for. Like you could have a main menu scene (which is always used) which places the object in DDOL. If you need only 1 instance of it, a singleton is also fine and you can place it in every level then. This would help in editor since you wouldnt want to open the main menu scene to test something in a specific level
Yeah, I want this to work even if I'm loading an arbitrary level.
Hmm, I was going to have each instance of the object check if it's the oldest and if not destroy itself, but that means I can't configure values across multiple scenes.
Sounds like I would need an editor script or something.
I'll do it manually for now and deal with the conflicts later.
The easiest way is the singleton pattern. If the static instance is null, assign the current object as the instance. If it's not null, then destroy the current component or game object
And also place in DDOL if the instance is null
Think I found something
Itll work across multiple scenes, the object in your new loaded scene will just destroy itself
there's a UnitySingleton repo in Unity Community that uses the build system
Im trying to access child objects in a player character i have but i get this error
how do i fix it?
this seems more related to the rig of your character, instead of something to do with accessing child objects. are you moving the objects or something?
im using animations and models from mixamo, and the mixamo rig object is under a gameobject i made
but the animations still play as normal
im doing some testing and that seems to cause that error
but the error pops up after i refresh the animator
when i click on some other object with an animator
im unsure but this doesnt seem related to a code question then, maybe something got moved around in the hierarchy so your rig doesnt match 🤷♂️
yeah its not a code question, is there a differnet spot i should ask in?
and now the problem seems to be solved, but i think the error might happen again so still unsure
#🔎┃find-a-channel tells u which every channel is for
oh it seems like they changed the layout
if i get the issue again ill ask in #🏃┃animation since thats probably the correct channel
thanks for the advice
Hello, is there a way to check for raycast on a non-convex mesh collider in Unity? I have a zone/district mapped out with a non-convex Mesh Collider (they are located above the terrain around 100 units) and I want to be able to detect in which zone/district I am with a raycast up from the player
I've tried raycast and sphere overlap but none of them work
how do i use memory profiler, i installed it but where do i go
https://gdl.space/hajevacufi.cpp
I'm trying to create a square based mon isometric sprites that means that each sprite on the screen looks like a rotated pixel art tile i want it to allign correctly but right now it's not working
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
@silent shuttle
Debug.Log("So the code is formatted like this, and is easier to read"
hard to read code like that
howm do you ge it to look like this?
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
^^^^^^^
@pseudo nymph here's it with the link thing you wanted can you see what i need to change so it ligns up how i ant it
this isnt a workflow I'm famliar with, I can't help ya, just directing you how to better format help requests so you're more likely to get an answer
your problem description is vague, and full of difficult-to-read typos as well, might help the helper if you cleaned that up :D
i want it to align like this basically
it's in a zigzag patern but i want them straight
mayb that makes more sense
I have a custom event system I've been working on and realised that my event listener will call all the game events in it's list rather than a specific one, any suggestions to improve this?
Event Listener:
public class GameEventListener : MonoBehaviour
{
[Tooltip("Event Item")]
public GameEventListenerItem[] eventItems;
private void OnEnable()
{
foreach (GameEventListenerItem eventItem in eventItems)
{
eventItem.gameEvent.RegisterListener(this);
}
}
private void OnDisable()
{
foreach (GameEventListenerItem eventItem in eventItems)
{
eventItem.gameEvent.UnregisterListener(this);
}
}
public void OnEventRaised(Component sender, params object[] data)
{
foreach (GameEventListenerItem eventItem in eventItems)
{
eventItem.response.Invoke(sender, data);
}
}
}
[System.Serializable]
public class GameEventListenerItem
{
[Tooltip("Event to register with.")]
public GameEvent gameEvent;
[Tooltip("Response to invoke when Event with GameData is raised.")]
public CustomGameEvent response;
}
[System.Serializable]
public class CustomGameEvent : UnityEvent<Component, object> { }```
Game Event:
public class GameEvent : ScriptableObject
{
public List<GameEventListener> listeners = new List<GameEventListener>();
// Raise Event on all subscribed listeners
public void Raise()
{
Raise(null, null);
}
public void Raise(params object[] data)
{
Raise(null, data);
}
public void Raise(Component sender)
{
Raise(sender, null);
}
public void Raise(Component sender, params object[] data)
{
for (int i = listeners.Count -1; i >= 0; i--)
{
listeners[i].OnEventRaised(sender, data);
}
}
// Manage Listeners
public void RegisterListener(GameEventListener listener)
{
if (!listeners.Contains(listener))
{
listeners.Add(listener);
}
}
public void UnregisterListener(GameEventListener listener)
{
if (listeners.Contains(listener))
{
listeners.Remove(listener);
}
}
}```
I have a custom event system I've been working on and realised that my event listener will call all the game events in it's list rather than a specific one, any suggestions to improve this?
The system is just these 2 scripts
Looks like this in the inspector
Instead of subscribing the GameEventListener, subscribe each of the items to their own events.
Hey!! Would anyone happen to know if there's a way to programmatically check if headphones are plugged in or not on Windows and/or Mac? Or even a means to see if there are any currently connected audio devices. Documentation isn't giving me anything
the listener is what is subscribing, it keeps an array of the events it is subscribed to
I see that. But you lose information like that. Specifically, you lose the info of what event is being processed.
so are you saying create multiple listeners each with a single event subscribed?
Can anyone help me please, im trying to make it so when u die in my game it displays how manu coins you got as well as resetting the coins counter so when u press retry it is bacn in 0
Simple: your IDE isn't configured
thank you, however i thaught the same and i asked it to show me the definition and it found it
i may be wrong however if it didnt actually exsist it wouldnt find it
Further proof it's not properly configured because it's seemingly unaware of your assembly definitions
Or maybe you just need to regenerate package files or something
The error is real though
ok there is like 2/3 diffrerent ones, should i send all?
this sounds about right, i feel like ive done this
dm them to me
Probably need to add a reference to your assembly
ok
okay thank you i will try figure this out
No. That's not what I said. In the first place I don't entirely understand the purpose of this event manager as it just adds a dependency without providing any useful functionality. And e
It even introduces the issue you're facing.
Is it possible to do something similar to this picture but inside a Unity TextMeshPro Text Component ? I have a similar photo added between text segments like this : <size=95%><space=12.5em><sprite="mural" index=0></size> . I would like the picture to be bigger and to be able to be slided left and right so the user can see it completely.
i'm no UI expert but i'm pretty sure you can't do that all in a single TMP_Text component, you'll probably need at least a ScrollView for that scrolling action. but you can always ask for help with setting up your UI in #📲┃ui-ux
I am doing my first project with the new InputSystem and would like to enable local multiplayer, I create an InputUser with _user = InputUser.PerformPairingWithDevice(Gamepad.current /* TODO: Device detection */); how do I now actually get input from that user? Usually I did with InputSystem.actions.FindAction(...) but that doesnt work on _user.actions
For your first project you should use PlayerInputManager and PlayerInput which handles all this for you
Nah, first project with the input system, not first one in general 😄
Ill take a look at those two tools, still, is it possible to get them similar to FindAction()?
is there anyway to detect the collision only once using raycasting?
i used bools to detect if it has been hit or not but it didnt work.
any other way?
what do you mean by it didn't work? that should work just fine
its not like "didnt work"
my code is not mono so thats why
that doesn't explain anything
well i tried to instantiate a particle effect when hitting an object tagged sth it kept instantiating them for ever this also happens when i use debugs , it keeps spaming it in the console for ever
show the code
1sec
Is it possible in general at all to get them the same way? I promise I will try your suggested method first, I just want to test the available options, if it was purely local multiplayer, your solution would 100% solve my problem, thing is I network over steam and instead of sending the input from the player object to the network systems just to funnel the movement data back to the player i want to catch the movement data directly in the systems that handle sending the input, so if its possible, I'd like to atleast have a look what works better for me
Pastebin.pl is a website where you can store code/text online for a set period of time and share to anybody on earth
GameManager :
https://pastebin.pl/view/98178c55
Pastebin.pl is a website where you can store code/text online for a set period of time and share to anybody on earth
and where are you doing anything at all that would attempt to make sure you are not hitting the same object more than once?
well i used bools but they didnt work
wait i will try again and show you
this happens
also if you want to hit everything in the line, why not just RaycastAll instead of recursively raycasting if you hit something?
why are you using a 3d raycast for 2d?
its a long story
but is that the problem?
then you'd better start telling that story
well a 3d raycast will not detect 2d colliders
no i use 3d colliders
the objects are cubes
why
perhaps because you were doing something fundamentally wrong with the 2D colliders
no i checked it a hundred times
it worked
but not as well as i wanted
and what was the problem?
.
This does not tell me anything.
.
holy shit dude
.
if you're not going to actually answer questions, don't expect to get help
what do you want me to answer
i told you what happnes
and the code
I do not understand why you could not use 2D colliders.
in case it is unclear: I am asking why you decided you have to use 3D colliders
i wanted to turn the game 3d in some levels
Okay. That is a reasonable explanation.
2D and 3D engines are super different
not a very long story, now is it
and do not communicate with each other
your 2d levels don't need to use 3d physics just because you have other scenes that use 3d
but anyway, i've already suggested a solution to your issue
i dont think thats the problem
why don't you go read back through the conversation
do you mean you only want to raycast once, and return 1 result?
wdym
i hope you also realize that doesn't really show what you are trying to fix
You are not communicating very clearly. I can't see anything "wrong" with that screenshot.
you see the particle?
yeah. you just need to implement the behaviour
Take two minutes to compose a clear explanation of what is wrong.
you mean there should only be one yellow dot?
i feel like I’m playing charades with code
it keeps instantiating a particle effect for ever
thats it
Okay. That is your problem: the code that winds up spawning particles is running more frequently than it should.
oh, so this is a VFX issue
is the particle system being instantiated repeatedly, or is it that the single particle system is continuously spawning particles?
Good point.
Perhaps it's not a code issue at all.
I think Rad said that the console was "getting spammed"
yeah when i use debugs
VFX graphs use visual scripting, so still technically code
but not a C# code issue, potentially
no its just the one single particle system
there we go. so where do you tell the particle system to stop playing?
first, are you using a VisualEffect component, with VFX graph?
are you sure? you said that you're "getting spammed" with logs. that sounds like your code is running over and over
Verify this before you continue. See if there are many particle systems or if there's just one particle system.
To solve a problem, you must have information.
idk much about using particle system without vfx graph, so I need to dip
no that getting spammed with logs
was for the collision detection
you should unfold the scene in your hierarchy so you can actually see how many particle systems there are
but thats the problem i think
You must replace "I think" with "I know".
^
When I am debugging bad behavior, I try to rule out as much as possible.
sorry i got disconnected
wait
i will get an ss
Okay, so now you've confirmed that you're spawning way too many particle systems.
so then it was not "one single particle system"
i meant the one particle system is spawning
i misunderstood
else if (hitInfo.collider.gameObject.CompareTag("Mirror"))
{
Vector3 pos = hitInfo.point;
Vector3 dir = Vector2.Reflect(direction, hitInfo.normal);
GameManager.instance.SpawnHitParticle(hitInfo.point);
CastRay(pos, dir, laser);
}
I presume this is the offending code. You reflect the ray with the hit normal and then cast it again.
I wouldn't be surprised if you were just hitting the surface again and again
I would suggest logging the hit point and normal to give you some more information.
But, assuming that's the cause, you will probably need to add a little bit of "wiggle room" so that the raycast doesn't just smack into the surface again.
You could move the origin slightly.
Although, actually -- if it was doing that, I'd expect infinite recursion that crashes your game.
It's more likely that it's just spawning a new particle system every frame and building up a huge pile of them.
Verify this. Pause the game and watch what the hierarchy is doing as you advance frame-by-frame.
yeah i think the same
should i try destroying it?
i used the same with the laserbeam object
Destroying the particle system would mean that the particles don't get to spread out.
I'd have to think about that for a minute.
One option would be to spawn many particle systems, but have each particle system only spawn a few particles
and then die after a few seconds
Another would be to move the same particle system from place to place (after setting it to use world space, so that the particles don't follow it)
This sounds easier. I don't know what the performance cost would be.
You'd have way more particle systems in total.
The VFX Graph would actually be pretty useful for this situation. You could just have one Visual Effect component that you ask to spawn sparks wherever the ray hits
yeah this one is fine
If it gets too heavy, you can always slow down the rate that you spawn particle systems at
but how should i destroy them after few seconds?
i have no idea how to do that
the Particle System component has an option to destroy itself when all of its particles are gone, iirc
Figured it out
public class PlayerView : MonoBehaviour
{
private InputActionAsset _inputActions;
private InputUser _user;
private InputAction _moveAction;
private void Start()
{
_inputActions = InputSystem.actions;
_user = InputUser.PerformPairingWithDevice(Gamepad.current);
_user.AssociateActionsWithUser(_inputActions);
_moveAction = _inputActions.FindAction("Player/Move");
}
private void Update()
{
var v = _moveAction.ReadValue<Vector2>();
if (v == Vector2.zero) return;
Debug.Log(v);
}
}
You could also only have 1 particle system and make it follow the impact position
alright
appreciate the help
Fen and dlich i think im going to restart the entire movement unless you want to fix it i feel like that redoing the movement would be faster then solving the issue
maybe a simple one - is there an accepted / best practice way to set an environment name (development, staging, production) for a client (eg unity desktop) build? tried a custom build script to accept env name as an arg at build time and set it to a class that hopefully was going to be read at runtime, but of course, that value doesn't persist at runtime bc the vars are reinitialized to defaults.
is there a place in project settings.asset i can stick an env name? i thought about appending a char to build version, e.g. 1.0.1d (dev), 1.0.1s (stage) ...
I have not done this before, but perhaps you can generate a TextAsset at build time that contains the string you want
I'd probably just stick it on the end of the version string
You should use preprocessor directive. This way you can add extra feature in the dev environment like cheat or analytics.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives
it's more than that, i need an env name at runtime to be able to decide which services to connect to
You also can use launch parameters.
https://learn.microsoft.com/en-us/dotnet/api/system.environment.getcommandlineargs?view=net-7.0
i mean, in that case, you could just do
#if florp
public static thingy = "foo";
#elseif blarp
public static thingy = "bar";
#else
public static thingy = "baz";
#endif
That member is guaranteed to exist, but its value will vary
I was originally thinking of using defines directly, but C# doesn't do that, iirc
(i.e. doing #define BUILD_KIND "Release" like you would in C)
hmm yea but then wouldn't my players have to launch the game from their respective command lines with an "environmentName" arg?
You can do a default. If there is no command use production otherwise use dev
looking like i'm going to use a prebuildaction e.g.
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
public class PreBuildActions : IPreprocessBuildWithReport
{
public int callbackOrder { get { return 0; } }
public void OnPreprocessBuild(BuildReport report)
{
// Load the ScriptableObject
GlobalSettings settings = AssetDatabase.LoadAssetAtPath<EnvironmentSettings>("Assets/PathToYourScriptableObject/GlobalSettings.asset");
if (settings != null)
{
settings.EnvironmentName = (populated from arg passed to build)
// Make sure to save changes to the ScriptableObject
EditorUtility.SetDirty(settings);
AssetDatabase.SaveAssets();
}
}
}
If you are to do that, you can use.
string GetEnvironment()
{
#if DEV
return "DEV";
#elseif PROD
return "PROD"
#else
throw new NotImplementedException();
#endif
}
anyone know why this is here; in visiual studio it has no problems with my code but it still says this for some reason
Beacuse that's a null reference, which happens at runtime. Your code won't have an issue with it until it becomes a problem.
So whatever is on line 30 is referencing something that doesn't exist.
why is gravity not being applied?
moveDirection.y = movementDirectionY - gravity * Time.deltaTime;
moveDirection = (forward * curSpeedX) + (right * curSpeedY);
swap these lines around
you're setting the gravity, then immediately overwriting it
thanks, it works now
no probs!
how can I get a gameobject thats a child thats named "laser"
sounds like you should be putting a component on this object called "Laser Holder"
rather than just searching for something by (child) name
transform.Find("laser")
so make a class thats empty instead?
but @heady iris is right, searching each time you want it isn't great
Yes. Or just referencing the laser directly.
should only grab it once at startup
Why do you need a parent object? Is the player rotating this object, perhaps?
In that case you definitely want to create a component that represents "a thing you can rotate"
not sure why the ❎ , that's literally how it would be done, regardless of other solutions
bad practice to reach into the innards of other objects
agreed
so its better to create an empty class and search for that object instead?
You've given us the "Y" in the XY problem.
need to grab to disable/enable it at certain times
I'll just grab the laser from another script that already has it serialized 🙂
wait, so you want the laser itself, not its parent game object?
Lasers is a parent that has 3 children that make up the laser
then you should really have a Laser component
something that lets you reason about this contraption without caring about exactly how many children it has and what they're named
so I should have
public class lasers{
//this class is empty}```
another alternative, if the laser will always be there, you can also define it as a public GameObject Laser in the class you want to use it in, and drag the correct gameobject into it on the inspector
no, you should have a class like
public class LaserEmitter : MonoBehaviour {
public LaserSource source;
public SomeOtherPart anotherPart;
}
i don't know how this is set up
if you want to disable the laser source, now you can directly access it and turn it off
you can also do other useful things, like set its color or change its max range
or whatever else you might do in your puzzle game
You should move the code that belongs to the Laser into the Laser script, I assume shooting a light beam and all that stuff
GameObject references are rarely the right choice. They give you very little information and are very easy to mess up.
since you can drag literally any game object into the field
if you reference a LaserEmitter, you can only assign a laser emitter into that field
its literally just a line that does nothing
and you can easily do things to the laser emitter
instead of having to search for random components and children
you want your code to be easy extensible just in case
There's nothing stopping you from having a big pile of GameObject fields, but you'll also find yourself making more mistakes
I prefer to get rid of as many ways to make mistakes as possible.
(i already have enough as-is)
at most I use a Transform field just by principle
yeah
if I actually want a Transform, I use a Transform field
I use that to mark where to attach UI elements, for example
public Transform itemHolder;
in this case, I really do not have any thing more specific in mind than a Transform
it's a conceptual match
public GameObject verySpecificKindOfThing; is bad
whats the use in grabbing transform if I just want to setactive
yep
Then make your code do that
that would be gameobject.SetActive(true)
just make a laser script
It might, under the hood, just deactivate the game object
But now your code is much more clear
laserSource.TurnOff();
or laserSource.emitting = false;
This code turns off a laser
agreed, if you have your laser script just have a public void ActivateLaser(), for example, the other places that use your code won't need to be changed if y ou decide that it will do more than just activate the gameobject
It's very obvious what it does, and it can't possibly be turning something else off
indeed
and you probably will decide this at some point
maybe you want to "break" the laser until the player performs an action
if you just directly activate the laser's game object, you're going to have to change every single place you do that
or spawn some particle effects, etc
to make sure the laser isn't broken
encapsulation makes your life so much easier
I'm making some sweeping changes to how a game I last touched 6 months ago works
but because most of the details are encapsulated, it's been remarkably easy
The player now takes a few frames to spawn because I have to additively load a scene or two first
all I had to do was change the one place that deals with telling everyone that the player now exists
if I had lots of Transform.Find("Player") all over my code, it'd be a nightmare
(and it'd break, because the player's name changed)
I have components whose sole job is to reference other components
Components are cheap. Your time isn't.
@heady iris @cosmic rain LMFAO i got it to work and im actually devestated that this was the issue after doing all that major work
...huh, interpolation did it?
That's really weird.
I guess it could malfunction if you were setting position and rotation outside of FixedUpdate
since the interpolation would be trying to apply during Update
That could be it.
i guess so but ngl interpolation was the last thing i'd think about
i tried creating a new character controller and after turning on interpolation it did that weird thing
You saw the behavior change when going below 50 fps
I might try reproducing this later
it has very low impact to the camera script on itself, however when i enable the movement script i just created it starts again with those huge spikes
let me throw the script in here for you to utilise
Hello maybe someone can help me here. Im using Unity Gaming Services Authentification and implemented the register with username / password. All is working fine. What is the best place to safe the Username ? Maybe I can search on dashboard with name and not with playerid .. ?
laser = fighter.GetComponent<LookAtEnemy>().laser?.gameObject;
throwing error when laser is null...did I put the ? in the wrong place?
laser = fighter.GetComponent<LookAtEnemy>()?.laser.gameObject;
``` this also didn't work
I got around it another way...but still confused on why this doesn't work
simply add an if statement to check if the laser is null
call this only when laser is not null
I "should" be able to use the ? somewhere to avoid having to add another if statement iirc
? and ?? do not work correctly on Unity Objects. The docs are pretty clear on this
unity overloaded == null to check for object destruction