#archived-code-general
1 messages ยท Page 206 of 1
yeah, i was changing it in the code like a dumbass
hey does anyone know if you can buffer the drag speed of a slider?
I have a slider controlling an animation and need it so people can't blast through
has anyone also made like a slider to control the point in time an animation is at
Im not sure if it's as simple as this
{
private PlayableDirector playableDirector;
[SerializeField] private Slider timeScrollerslider; // retrieve the slider component from the gameObject
private float animationDuration;
void Start()
{
playableDirector = GetComponent<PlayableDirector>();
animationDuration = (float) playableDirector.duration;
}
void Update()
{
playableDirector.time = animationDuration * timeScrollerslider.value; // call in update every frame?
}```
Is this how would you consume an IAsyncEnumerator in a coroutine?:
IAsyncEnumerator<DigimochiNFT> digimochisProducer = DigimochiNFT.GetAllDigimochis().GetAsyncEnumerator();
while (true)
{
ValueTask<bool> task = digimochisProducer.MoveNextAsync();
while (!task.IsCompleted)
yield return null;
ExceptionDispatchInfo exception = null;
try
{
if (task.GetAwaiter().GetResult())
digimochis.Add(digimochisProducer.Current);
else
break;
}
catch (Exception e)
{
exception = ExceptionDispatchInfo.Capture(e);
}
if (exception is not null)
{
ValueTask disposeTask = digimochisProducer.DisposeAsync();
while (!disposeTask.IsCompleted)
yield return null;
try
{
disposeTask.GetAwaiter().GetResult();
}
catch (Exception e)
{
throw new AggregateException(e, exception.SourceException);
}
exception.Throw();
}
}
{
ValueTask disposeTask = digimochisProducer.DisposeAsync();
while (!disposeTask.IsCompleted)
yield return null;
disposeTask.GetAwaiter().GetResult();
}
Hi.. I've got a little problem with Singletons between Scenes..
my setup is that each scene needs some managers that are singleton classes (like AudioManager, CameraManager etc.), some of those should live between scenes. Eg. I'm on some portion of map and ofter player reach some point I want to load new part of map and unload old ones. I add to them DontDestroyOnLoad so their work won't be interrupted (eg. global audio like music won't cut off).
The problem start if I'll try to keep those manage systems also on those other scenes (eg. for testing) - what's the best way to takle that problem?
I tried to create one super-manager that has other managers underneath (at least those that need to be kept between scenes) and if he sees other super-manager (from newly loaded scene) destroyes itselt, but it feels overcomplicated and doesn't solve anything (I don't know how, but those 'destroyed' managers still exists and try to receive inputs etc.)
I am having the following issue:
I have a Script attached to a object that holds a reference to its own Transfrom.
When I Instantiate that object, that reference moves with the new Instance.
(The new instance is now holding a refence to itself)
Is there a way to stop that behavior?
My goal is to keep the reference to the original while instantiating.
have whatever instantiates the object pass the reference to the prefab back to the instantiated object. but why would it need that reference in the first place?
Ill take a look if I can do that (thinking about it, should be quite clear to implement (hopefully)).
The reason it has that reference is that this is a wave function collapse based Terrain gen, each tile holds its valid neighbours which in some cases includes themself.
However the way I collect and process these neighbours neccesitates the reference to the original
use Mathf.MoveTowards to move the time towards the current slider value
playableDirector.time = Mathf.MoveTowards(playableDirector.time, timeScrollerslider.value, Time.deltaTime);
this would go from 0 to 1 in one second
ok ok ill give it a shot and see if it smoothes the transition
clamps it too much
what i was thinking
is make a float buffer
like 0.80 then multiply that into animationDuration * timeScroller.value * buffer
probably will have a more controllable effect
hey guys can you swap a texture in unity at runtime
?
I have four different textures and would like to swap them out at runtime
What is your texture on? On a material?
material
I want to access these materials from the MeshRender
and change the textures within them
is this possible?
You can either create 4 materials and swap those
yeah I dont mind doing that
Yeah same for maintex
i saw this online you can get the component and call setTexture
but idk if it works for smth other than the normal
as shown here
but be advised, you are changing the material instance with it, it might affect other objects
so basically every object with that material assigned will have its texture changed?
i am not sure right now under which circumstances, but yes that can happen
your best bet would imo be to just swap between materials
instead of editing one material
the thing is i have scripts
that depend on the materials whose textures I am changing
and if i swap the materials there I'd need to swap them on all my acting scripts
which is why I wanted to try with textures first and brings me to a bit of a conundrum
The short answer: Then edit the materials
The long answer: Thats keeping state in the wrong place, create a state-holder script instead of reading from materials in other scripts
does anyone know why changing the vertices and triangles in a mesh doesnt show in the game?
I am trying to add vertices and triangles to a mesh, and even do the respective arrays have increased in size, the mesh remains thesame
odd question, in unity you can't create a copy of a component like you can a gameobject can you?
Hello. When running my game in the editor, FPS slowly drop over time, bottoming out around ~32. Then if I pause the editor and wait a few seconds, when I hit play it goes back up to ~72 fps. Slowly drops again, pause resets, forever
I've explored the Profiler but can't see any obvious culprits in there... any ideas?
I have run into a very weird coding case where i need to essentially copy the box collider from a child object to a parent object
Yes, I believe you have copy the values individually
garbage collection?
@rancid frost Seems like a likely culprit yeah, but it's almost more like garbage pileup? Cause of the gradual nature over time, until the pause.
ram usage steady throughout that time? I have seem unity editor's ram usage creep up sometimes then drop
Or maybe GC isn't running for some reason?
@patent hound You mean on my OS level, or w/i unity?
like the ram usage of unity within your OS
your profiler should tell u where the spikes are, I recommend you start there.
Can you show your code snippet?
@rancid frost I'm not seeing anything unsual in the profiler. Cause it's not really spikes
Not even seeing anything increase over time in there
begining disabling objects 1 by 1. you can pin down said problem
@patent hound That's interesting. Looking now, nothing is increasing in RAM or CPU. But it does jump to using ~240% CPU while it runs... I wonder if my Mac is throttling it? Never had anything like that but could be
you are very much running something cpu intensive
its ur code
Try using SetVertices instead of the = variant
i had a similar issue and it was because i was testing something and forgot to change back my virtual memory settings and unity would sometimes partially get pushed out to virtual memory on disk, figured i'd throw it out there as a possiblity. that's definitely odd
Oh nvm, meshFilter.mesh outputs a copy of the used mesh, reapply it to use the changes
doesnt work
strangely, the triangle count of the scene goes up accordingly....
but the vertices dont....
here is what I have now
@patent hound What sort of virtual memory settings were you tweaking? It definitely seems to be some OS level issue, I'm running another very simple project now and seeing the same behavior
@rancid frost It's not the code, ^^
I was trying to see how slow certain things would be on a system with less ram so i changed the virtual and physical memory settings in windows
Don't love the implications of my machine just slowing down.. maight need some fan cleaning
it was not a unity setting i tweaked
hmmm, did u disable all objects in scene 1 by 1?
sanity check here, does this code snippet work as described
//now we need to make a new box collider that encapsulates this object and the weapon inside //create a new box collider and bounds BoxCollider newBoxCollider = this.gameObject.AddComponent<BoxCollider>(); Bounds bounds = new Bounds(Vector3.zero, Vector3.zero); //check if we have a renderer and encapsulate it to start with if (transform.GetComponent<Renderer>() != null) { Renderer thisRenderer = transform.GetComponent<Renderer>(); bounds.Encapsulate(thisRenderer.bounds); } newBoxCollider.center = bounds.center - transform.position; newBoxCollider.size = bounds.size; //iterate through the children of this object //the weapon and other object we need for our purposes will have renderers on layer 1 so we do not need to iterate through all of their children foreach (Transform childTransform in gameObject.GetComponentsInChildren<Transform>()) { Renderer childRenderer = childTransform.GetComponent<Renderer>(); //if that child has a renderer encapsulate it if(childRenderer != null) { bounds.Encapsulate(childRenderer.bounds); } newBoxCollider.center = bounds.center - transform.position; newBoxCollider.size = bounds.size; }
@rancid frost Yes it's having the same behavior in a completely fresh/empty project
hmm
I dont know how to be of assistance
perhaps, u got some other program fucking with you?
check vsync maybe
that could be it
you are still adjusting colliders for components with no renderer, is that intended?
I wanted to ensure that the center and size were never null so i left the first one out of the if statement
however they don't need to be reset in the for loop you are correct
newBoxCollider.center = bounds.center - transform.position;
if the collider is on the transform, why subtract transform position?
any ideas?
Have you tried all that in a sample manner? If the vertex count changes it sounds like the error might be somewhere else in the code
Because that was supposed to be newBoxCollider.offset not newBoxCollider.center
good catch
vertex count changes in code, but the unity stats screen. It should vertex count NOT changing...triangle still changes tho
ill test some and then report back
What if you just use "clear" without assigning new data? Does the mesh disappear from the scene view? Does the info in the stats update?
only the tris count updates , vertex stays tehsame
ive tried using both clear and assigning new mesh...nothing
This is creating a new mesh. Are you using this method to modify it as well?
i simply old an array with the nesssaccary info, and assign them to the new mesh
For starters, I'd avoid relying on the statistics window. It's known to produce unreliable information for debugging.
You should step through your code, or inspect the relevant objects in the inspector. You can also see rendering info in the profiler.
But if the info in the statistics is correct, then perhaps your triangles array just doesn't reference the new vertices. In this case only the triangle count would increase.
I have stepped through the code
https://img.sidia.net/ZEyI5/ROfIMACi02.mp4/raw
This works, but only if I copy the verts into a new array and then apply it, directly applying the modifications to the vertices[index] did not work
Check the triangles array. Does it contain the new vertex indices?
using UnityEngine;
public class TestScript : MonoBehaviour
{
public MeshFilter Filter;
public void Update()
{
if (!Input.GetKeyDown(KeyCode.A)) return;
var mesh = Filter.mesh;
var vert = new Vector3[mesh.vertices.Length];
for (var index = 0; index < mesh.vertices.Length; index++)
{
vert[index] = Quaternion.Euler(45f, 0, 0) * mesh.vertices[index];
}
mesh.vertices = vert;
Filter.mesh = mesh;
}
}
yes, numbers of triangles and vertex look good
will give this a shot
nothing happens
Did you have a look at the mesh in the inspector?
uh
Not the frame debugger. Just double click the mesh in the mesh filter
nothing ๐ฆ
Does it update?
relative to what?
mesh A was 3 vertex
triangles are 0 1 2
mesh B had 3 vertex
triangles are 0 1 2
if u merge them...
Mesh B triangles are not 3 4 5
Merging meshes? I don't remember you mentioning that. But that might explain many things.
And yes, I've been telling you to check the indices in the triangles array from the start.
i know
i was checking if they werent empty ๐ฆ
https://img.sidia.net/ZEyI5/KOTahEKA81.mp4/raw
Is there any way to loose that stutter when moving the camera with my demo player object? No stuttering happens when the camera stays still
Camera syncs to the position of the player with a lerp in LateUpdate
private void LateUpdate()
{
if (!_changeDetected) return;
if (!Follow) return;
if (Vector3.Distance(_targetFollowPoint, _currentFollowPoint) < 0.1f)
{
_changeDetected = false;
return;
}
var cameraTransform = transform;
_currentFollowPoint = Vector3.Lerp(_currentFollowPoint, _targetFollowPoint, LerpAmount);
var rotation = Quaternion.Euler(Angle);
var offsetPosition = _currentFollowPoint + rotation * new Vector3(0, 0, -Distance);
cameraTransform.position = offsetPosition;
cameraTransform.rotation = rotation;
}
are u using any other cin machine component?
obligatory "use cinemachine"
he isnt using cinmacine
probably not since this script is inLateUpdate
wtf
Not using cinemachine at all
shit, why not?
right, which is why the advice i gave was to use it
Never touched it, guess i have some documentation to watch
you should @dusky lake
yup, nice catch. I just auto assumed he was
tell him that lol
thanks the issue is resolved! ๐
idk why discord does that sometimes lol it replies to wrong person soz
I am stupid, made the recheck distance to big
Anyways, now that it runs smoothly, lets remove it all and implement cinemachine ๐
I did something similar once you know, I didnt know what cinmachine was. spent days creating scripts to confine camera, move and all...damn I suffered
https://img.sidia.net/ZEyI5/PEFeSEzA92.mp4/raw better now
I guess i can make cinemachine follow a point instead of a gameobject?
Cause im calculating a center point of all active players for local multiplayer
Anyways, before asking questions, I should look at the feature to begin with ๐
I think you can only assign a transform target and add offset
eh, then i might aswell have an empty transform target
usually people do that , call it like "cinemachineTarget" or w/e
because some of the camera modes are affected by the target's rotation
https://img.sidia.net/ZEyI5/ZiyUtENe28.png/raw looks like i can save myself some calculations
and let cinemachine handle everything for me ๐
aight, you got me convinced, already in love with it ๐
My favorite part is Auto Blending between cams and also when I make a game in old Resident Evil style it has a camera auto camera switching when you're in range of certain cams
So what was the issue in the end?
Does OnTriggerStay2D stop getting called if the object it's on isn't moving?
Nope
Hmm, I don't know what's wrong then, but I think I found a workaround so I should be fine.
when merging 2 meshes, the triangles of mesh B needed to be increased
anyone know how to stop a charactercontroller bouncing when going down a slope?
You could snap it to ground below or move along the ground normal. I would use https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131 as a base.
why is my code not changing color. it works but if i make a mistake in writing the code there are no red wiggly lines which makes it harder to write code if i make a small typo. is my visual studio missing something
configure your !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
thanks
i suck at quaternions, is there a good way to put an object 1 unit in front of the player but only factoring in the y rotation?
essentially i want to place the object 1 unit in front of the camera but not factor in the up/down rotation of the camera, only the left right rotation
you don't need quaternions for that so i'm not sure why you prefaced your question with "i suck at quaternions"
you should be able to project the camera's transform.forward onto a plane with a normal of Vector3.up using the Vector3.ProjectOnPlane method
you may need to normalize the resulting Vector3 from that to get it exactly 1 unit away though
i was not aware of the projectonplane method, i thought i was gonna have to do some quaternion math
how to run video recorder on Built game?
like the Unity Recorder from Window > General > Recorder? because that's editor only
also not a code question
Window > General > Recorder? yes
if that is the recorder you are referring to, then it does not work in a built game. it is editor only
how to record video on game?
like just record your game window? that's not a unity question. nor is it a code question. but you can use software like OBS to do so
why are you using a game engine to do that
I don't need this one, what else can I use
why don't you do some research and find a tool that makes more sense to create a video player/recorder app in?
because I can use AI in unity
so your video player is also going to incorporate AI? or are you referring to using AI to help you make it because you don't actually know what you are doing?
well the recorder i mentioned earlier would not be appropriate for what you are trying to do because it doesn't do that. nor would unity be a good choice for creating a video player app
i have been struggling to understand the projectonplane function for like 2 hours lol, and after not getting it for around an hour i've started toying with it as a gizmo drawline and i'm now more confused
i'm using code similar to
cameraWorld = gameObject.GetComponent<Character>().GetCameraWorld(); Transform cTransform = cameraWorld.transform; Gizmos.DrawLine(transform.position, Vector3.ProjectOnPlane(cTransform.forward * 1, Vector3.up);
but i've tried switching the variables around, changing what i'm putting in the function and i am just not getting the results that are coming out
it's the fact that it isn't (vector, plane) that's confusing me, it's 2 vectors and my brain is just farting out getting what the second vector does
if you read the docs, you'll see that the second parameter is the normal for the plane. you don't need to define a whole plane for it, it just needs the normal for the math it does. your parameters for the method are correct. although i don't see why you've multiplied the cTransform.forward by 1. you do know that multiplying anything by 1 is just going to return itself, right? so that's a pointless operation
well it had a variable for distance there originally and i've just been changing small details one after another, simply did that instead of deleting it
okay so what is it currently doing that you are not expecting?
it's shooting a line off at a 45 degree angle that stays the same in world space regardless of what direction the camera is facing
you can see the gizmo line shooting off the player in the same direction even though i've rotated nearly 180 degrees
remember that the second parameter for Gizmos.DrawLine is the end position. not the direction.
you're getting the camera's forward direction projected on the plane with the Vector3.up normal. if you use that as a position it's going to be within 1 unit of the scene origin
well i had it as transform.position + the current projectonplane but that does other wild unpredictable things
try it now
you're right though that doesn't make sense the way i had it in that code snippet since it's not position,angle it draws the line between 2 positions
i got it figured out FINALLY it was because i wasn't spawning them far enough from the player object their rigidbodies were freakign out forcing them through the ground
making me think that the spawning was going the wrong direction and spawning them down
How can I make this work? I want other scripts to be able to call this function, inputting another function of their choosing.
public void AddAction(Action action)
{
GameObject instantiatedAction = Instantiate(actionItem, transform.position, Quaternion.identity);
instantiatedAction.transform.SetParent(contextMenu.transform);
instantiatedAction.GetComponentInChildren<TextMeshProUGUI>().SetText(action.ToString());
instantiatedAction.GetComponent<Button>().onClick.AddListener(?)
}
You need UnityAction
That's the type that onClick takes
Thanks
is it possible to run a unity api call as a coroutine? i need to recalculate the collider for a large tilemap, so i'm using a composite collider and calling GenerateGeometry(), but it hangs the frame for a moment. is there a way that i can make that function call run like a coroutine?
eg. StartCoroutine(collider.GenerateGeometry());
That's not how coroutines work. If you call a method in a coroutine it'll hang just the same as when called anywhere else
To avoid that you'd need to run it in another thread
hmm that probably won't work since unity api calls have to be on the ui thread right?
maybe i should investigate more efficient collider options
I created a procedural door mechanism that allows me to add/remove another door as a pair for the one that is already present inside the scene. When I add a door, everything works as expected but when I remove it, the mesh of the original door disappears and only reappears once I hit Ctrl+Z. The doors were created using Probuilder. Please watch the video in order to get a clearer picture of the problem.
Does anybody have any idea what could be the potential cause for this issue?
Is there a way to make this method show up in the Unity UI? I guess it won't show because of the enum ScoreSource
public enum ScoreSource { None, Bumper, Rollover, Slingshot }
public void AddScoreWithSource(int amount, ScoreSource source)
{
score += amount;
Debug.Log($"Add {amount} to score from {source}, netting {score} total score");
}
Here is the source code:
https://pastebin.com/4wvm3bRT - Mechanism
https://pastebin.com/NJ85VkuT - Editor Mechanism
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.
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.
You can't pass in multiple parameters through the inspector UnityEvent. One workaround for constant parameters for a given instance is to have a serialized field and passing that in the method you invoke.
Thanks for the heads up! I'm not sure I understand correctly how to apply the workaround in my case, I tried something like
[Serializable]
public class Both
{
[SerializeField]
public int score;
[SerializeField]
public ScoreSource source;
}
public void AddScoreWithSource(Both both)
{
}
But it may not be what you described, though I don't understand exactly what you mean
Just a regular field on the monobehaviour that is then used in the method
Is there a simple debugger I can do within unity to see what accesses the setActive function of a gameobject? Something is clearly interfering with my ability to set a gameobject to active properly and im trying to figure out what script is causing it
Oh yeah right, though it would defeat what I'm trying to achieve here
I guess I could do it in two methods, SetSource and then AddScore
public void SetSource(ScoreSource source)
{
}
Damn this won't even show up in the event UI, guess enums are not handled
Could this problem be Probuilder related?
Yea that appears to be the case
@oblique spoke I did understand what you meant... and it's alright!
Not as pretty as directly setting the arguments in the event UI directly, but that's alright!
Thanks ๐
Is it required to mark public fields with [SerializeField] ? or is it the norm now?
You don't need it for public fields
Provide some context. They are words
public class Entity : MonoBehaviour
{
// Start is called before the first frame update
private Rigidbody2D rb;
public float speed = 3f;
void Awake()
{
rb = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
public void Move(int amount)
{
rb.AddForceX(speed*amount);
}
}```
Why does Awake from base class never get called if I am doing something like this
```cs
public class Player : Entity
{
int input()
{
return Convert.ToInt32(Input.GetKeyDown(KeyCode.D)) - Convert.ToInt32(Input.GetKeyDown(KeyCode.A));
}
// Update is called once per frame
void Update()
{
//Input.GetKeyDown(KeyCode.E)
Move(input());
}
}
Convert is used when the input and output is known to be compatible
Parse is used when the input and output may or may not be compatible
why are you doing this lol
i guess that gives you a value between -1 and 1
I will have multiple enemys and a player that will all be able to move, its a way to not repeat code
I see no reason for Awake to not run on instances of Player. Why do you think it is not running?
Are you getting an exception when you try to use rb?
using a Vector would make more sense ๐คทโโ๏ธ
I have a rigid body attached to my player and the inspector doesnt see the rigid body when I make it public in the base class
I'm sure there's a TryConvert method somewhere, and Parse vs TryParse is definitely a thing. Without knowing what they're comparing it's fairly arbitrary. I would say converting is generally a straightforward transformation and parsing requires some more logic to determine a relationship, but hey, no info
Convert only contains a few Try* methods
I was not replying in a C# context just a grammatical one
I edited my message
if rb is a public field in the base class, then will appear on Player
if it doesn't, then you probably have a compile error that's preventing anything from updating in the first place
when rb is public, it shows in the inspector but I don't think the awake method was ever called because the inspector cant see the rigid body im trying to get in the game object
Did you mean that the rb field says "None (Rigidbody2D)"?
you can check if Awake is running by logging something in Awake
yeah
it does run
mb
If it says None then that gameObject didn't have a Rigidbody2D on it
but it does
im attaching the Player class to the object though
Show the inspector.
Before I even try, how easy / hard / impossible would it be to make a component that runs on update that imitates the Symmetry behaviour pictured here? Context that is 3dsmax.
Is this something totally nontrivial and I shouldnt even attempt it? Or do you imagine its very do-able? Maybe a stock asset in some github exists with this done already?
is that in reply to me or someone else? I know you can run scripts in editor but that doesn't answer if the above is even possible to write
looking at it it doesn't feel impossible, the two things happening is its cloning the mesh along an axis, which feels simple, and unions them if they intersect on that axis, which feels way harder to do
Oh interesting, that does appear to be what I was looking for, Ill google what this UModeler X package is
true. true. anything is possible with enough knowledge ๐
๐ sure that answer is technically correct but it doesnt answer the spirit or intent of my question. It kind of hurts to be given such a pedantic reply.
the real question that we both know I was asking is how difficult will this be, am I going to go into development hell and become immensely frustrated by repeated failures to achieve this effect because I don't realize how challenging its going to be
Yeah I suppose so.
Thought you were looking for assets that does it similar thing instead of wanting to write the whole feature.
Sorry its all I got
I apologize as well I was not clear
If no stock asset exists I was going to try to write it myself
how can we possibly know what you will find difficult?
Why do you have to fight me instead of just answering the question? Sorry I even asked
I dont understand why developers find it so incredibly important to attack and challenge anyone who reaches out for help instead of fostering a welcoming and supportive environment
maybe you're just taking things a little too personal or as implied criticism lol
I can't speak for others but I have really bad people skills, but I do wanna help
I do not know how hard it would be. To me, it looks like the main challenge will be slicing the mesh along the plane of symmetry.
The rest is trivial.
(perhaps other than welding vertices together at the plane of symmetry, if you need that)
After you cut the mesh across the symmetry plane, you just need to reflect all of its vertices across the plane. That's basic math.
I suppose you'd also need to flip all of the normals, since the winding order would be backwards.
This is the part I do not know much about.
To answer the question asked, yes it can be done, I would find it very trivial to do, how difficult it would be for you I cannot say
it's easy to decide if each vertex should be kept, but producing new vertices to replace those that got chopped off sounds a little harder.
Pretty cool stuff but why update specifically? I assume there's a lot of verts to get that neat bendy look.
I would expect there to be at least one mesh manipulation package that can do this kind of thing.
There are quite a few for doing runtime object shattering, for example
Cutting an object in half is the hard part of this problem
Idk what i imported but i got this Asset Unlock - 3D and now my game is broken. how do i go back?
broken how?
can you just revert it in source control?
u can just delete the Asset Unlock - 3D
some of my layers got removed. and if i delete the folder the materials dont show and it turns pink
i have some changes in the materials. wont that revert it too
you probably imported the project settings too
yeah
which you should probably not have done
You don't have a commit?
i do
so revert
wasnt materials working when you made committ
It looks like that asset collection is designd to be used with the universal render pipeline. Were you using the built-in render pipeline?
no i was using URP
or otherway around
the project now looks at the new URP for some reason
Select one of your materials that is broken and show me the inspector.
i have been building logics and only worked on materials yesterday.
you Imported Project Settings when youimported asset so it changed everything, double check what Graphics settings your project has
yeah, let's see what the project settings look like
hmmm
i put urp and now the materials show
but some of the layers are gone too
that was a big part in the scripts
The layer numbers will not have changed
just the name of each layer
you can reassign them pretty easily
use proper version control to prevent this in the future
on it
I decided to try and play with a new movement system today using the character controller. I'm trying to use the .isGrounded but for some reason it's not seeing that my player is grounded and my player is floating in the air by .02
Using Debug, when the player is standing still it shows controller.isGrounded to be false, however when I start moving the player is flips between true and false
I am using the network manager to spawn in the player
Well now it is showing true for isGrounded, but only when the player is moving
Shouldn't it still show "True" even when the player is sitting still?
CharacterController.isGrounded only returns true when the last call to .Move involved pushing it into the ground
so it's generally annoying to use
and doesnt work in a lot of situations
most people implement their own grounded check
So even if the move command is used, but the player doesn't actually move, it doesn't matter. The player has to physically move for it to check
I have List<Transform> TopPatrolPoints initialized in inspector. When I try to debug. log this.TopPatrolPoints[0].position.x (line 103) I get error: MissingReferenceException: The variable TopPatrolPoints of Bartek doesn't exist anymore.
You probably need to reassign the TopPatrolPoints variable of the 'Bartek' script in the inspector.
If anyone got a simple pistol script that shoots and stuff dm me it for Unity VR
this isn't the place to get free handouts of completed code
chill it was a question
chill it was an answer to your question
if you want to not be lazy and actually put in literally any amount of effort to make your game, then i suggest you watch some tutorials or something. there are plenty that go over how you can make a weapon
A no would work ๐
Quick question: I wanna freeze my Z position in 2D movement. I wanna do it by: The declaration is at the top of my class and the target transform in my update method
target.transform.position.z = 0.0f;```
It gives me an error and says: "The return value of Transform.position is not a variable and therefore cannot be changed"
Then I tried to store it in a Vector3 variable but it didn't do the job either
Like that: private void Start() { Vector3 lockedZpos = transform.position; lockedZpos.z = 0; target.transform.position = lockedZpos; }
And set the lockedZpos.z 0 in the Update method
dont cross post, but you have already post the errors here
start only runs once, you should put it in update
Any ideas?
if its a rigidbody just freeze constraints
I did now, but still doesn't do the job
it's not a rigidbody, it is only transform
hmm show the current movement
Oh it's complex ๐
I am doing a game where you can switch between 3D and 2D
{
[SerializeField] private Transform target;
[SerializeField] private MouseSensitivity mouseSensitivity;
private Vector2 _input;
private float _distanceToPlayer;
[SerializeField] private CameraAngle cameraAngle;
private CameraRotation _cameraRotation;
bool use2DPerspective = false;
private void Awake() => _distanceToPlayer = Vector3.Distance(transform.position, target.position);
public void Look(InputAction.CallbackContext context)
{
_input = context.ReadValue<Vector2>();
}
private void Update()
{
_cameraRotation.yaw += _input.x * mouseSensitivity.horizontal * Time.deltaTime;
_cameraRotation.pitch += _input.y * mouseSensitivity.vertical * Time.deltaTime;
_cameraRotation.pitch = Mathf.Clamp(_cameraRotation.pitch, cameraAngle.min, cameraAngle.max);
if (Input.GetKeyDown(KeyCode.C))
{
use2DPerspective = !use2DPerspective;
Camera.main.orthographic = use2DPerspective;
if (use2DPerspective)
{
Vector3 lockedZpos = transform.position;
lockedZpos.z = 0;
target.transform.position = lockedZpos;
mouseSensitivity.horizontal = 0;
mouseSensitivity.vertical = 0;
Camera.main.transform.eulerAngles = new Vector3(transform.rotation.x, transform.rotation.y, transform.rotation.z) * 0;
}
else
{
mouseSensitivity.horizontal = 20;
mouseSensitivity.vertical = 20;
}
}
}```
{
if (use2DPerspective == false)
{
transform.eulerAngles = new Vector3(_cameraRotation.pitch, _cameraRotation.yaw, 0.0f);
}
transform.position = target.position - transform.forward * _distanceToPlayer;
}
}
[Serializable]
public struct MouseSensitivity
{
public float horizontal;
public float vertical;
}
public struct CameraRotation
{
public float pitch;
public float yaw;
}
[Serializable]
public struct CameraAngle
{
public float min;
public float max;
}```
so you were setting it on Update but moving in LateUpdate ? ๐คจ
hmm yeah thats gonna give you weird jitter iirc
also why not Cinemachine lol
2 cameras. . job done
I tried sooooo many variants and I only managed to do it like that
Movement which works in 2D and 3D
hello, so i'm currently working on a multiplayer system, so I made this code that work with my serveur with web socket. This code work fine but the problem is that I can't have more than 2 player connect at the same time because the code decript all the message he received and applied all of them to one player so if the data come from 2 different player the ennemie player in your game will applied to himself 2 diffรฉrent location, So I wanted to know what will be the best way of making the multiplayer work with more than 2 people , how I can and what's the best for making an instance for each player based on their ID that the serveur give me and apply for each of them specific value like their coordinate or if they receid damage...?
(sorry for my bad english ๐
)
Does anyone have any ideas on why there is never a tile found?
if(gridManager)
{
Vector3Int pos = Vector3Int.FloorToInt(HitPosition.position);
Debug.Log(pos);
Vector3Int cellpos = gridManager.waterMap.WorldToCell(pos);
Debug.Log(cellpos);
Tile tile = gridManager.waterMap.GetTile<Tile>(cellpos);
if(tile != null)
{
Debug.Log(tile.name);
}
There is a tile where the position is, there is a gridmanager, so I don't know
so any ideas? ๐
position and cellpositions seems OK
On what ?
havent done custom cams too much, i just use cinemachine
Get sprite still works for some reason
freezing my z position in the 2d view ๐
I just know cinemachine
and with that is very simple.
why are you doing FloorToInt on HitPosition.position?
You should do WorldToCell directly on HitPosition.position without any transformations
Flooring the position moves it out of the cell probably
maybe it put you under the floor
Flooring is always wrong here, because tiles aren't necessarily aligned to a 1x1 grid
yeah but the water is a LOT of water, so even if it would get moved out it would still be in a water tile
i'm thinking about the third dimension
hmmm
hey gang im having issues applying a knockback to rigidbodies where if i shoot a corner it gets knocked back and properly twists in a realistic way, as it stands it seems its applying the force to the center of the game object regardless of where i shoot
this is how im applying the force
hitRigidbody.AddForce(mainCamera.transform.forward * bulletKnockback, ForceMode.Impulse);
AddForceAtPosition
with the direction being the same as you do now
the position the hit position
literally just joined to ask a question
If you want it to spin, you need to use https://docs.unity3d.com/ScriptReference/Rigidbody.AddForceAtPosition.html
This will allow you to apply a force to an object somewhere other than its center of mass
Inferior formal answer
oof this may be more complicated than expected. cause im saving all the hit objects into an array on shoot and processing them after the shooting/damage/bullet decals happens
well, you just need to remember the hit point
you can save a raycastHit[]
ye, probably save it along with the object
can't you?
If you currently store a single Vector3 for the force or something, just replace it with a struct that holds all of the data you need
I think that's safe?
is that question?
I know you can get punked if you try to re-use Collision objects, because that's a class, not a struct
unity will reuse the same object for every collision message
well it's worth a try, @sharp lotus , do it for science
rb.AddForceAtPosition(forcedir * amount, raycasthit.point et.c.

my god
this is the third answer
oh wops m bad I just saw it now
my internet delays sometimes
mcdonald quality wifi
oh im dumb lmao.. im saving the list of hit objects like so
hitObjects.Add(hit.transform.gameObject);
only need to remove everything after "hit" LOL
right, that would store the entire RaycastHit
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
oh yeah
that's probably center of mass
oh true
I mean hit.point
indeed
(or, at least, something vaguely close to center of mass, and something that doesn't depend on the point you hit)
๐
hey so my the first line is correctly instantiating the game object but it is not setting the refrence
GameManager.Instance.activePlayer = Instantiate(playerPrefab, transform.position, playerPrefab.transform.rotation);
GameManager.GameEvents.onPlayerSpawned.Invoke(GameManager.Instance.activePlayer.transform);
the error is
NullReferenceException: Object reference not set to an instance of an object
anyone go any ideas why this is not working
this is way too little context
how much more do you need
Then playerPrefab is missing, or gamemanager is
yeah
tyty
This is so funny
discord scrollback gets me again
Any ideas?
Add a player ID to your WebSocket messages then only process the messages if the ID matches the current player
It's not multiplayer game
Hi. I just started learning unity 1 week ago, and I wanted to make a flappy bird game. I already have the bird movement, but I just need to spawn the pipes and make them move. Can you help me do it pls?
there are literaly hundreds of online resources on that
there are plenty of tutorials for flappy bird games in unity, you should go check some out
then you should start by learning the basics. there are beginner c# courses pinned in #๐ปโcode-beginner and the pathways on the unity !learn site are a good place to start learning the engine
๐งโ๐ซ Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
https://youtu.be/hKGzSYXPQwY This seems quick and seems to do the job
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
Show your Support & Get Exclusive Benefits on Patreon (Including Access to this project's Source Files + Code) - https://www.patreon.com/sasquatchbgames
Wishlist Veil of Maia! - https://store.steampowered.com/app/1948230/Veil_of_Maia/
Make flappy bird with this quick Unity tut...
Sorry read the wrong question. Can you post your code again but correctly this time
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Thanks ๐
Here it is
Man, do you not understand 'correctly'? Use a paste site
oh, sry
here is the link
a powerful website for storing and sharing text and code snippets. completely free and open source.
And here is the problem:
I have List<Transform> TopPatrolPoints initialized in inspector. When I try to debug. log this.TopPatrolPoints[0].position.x (line 103) I get error: MissingReferenceException: The variable TopPatrolPoints of Bartek doesn't exist anymore.
You probably need to reassign the TopPatrolPoints variable of the 'Bartek' script in the inspector.
OK, this is probably caused by your Coroutine running after you have done the Destroy(this).
you need to cache a reference to the Coroutine when you start it and then Stop the Coroutine using this reference before the Destroy
It's not this, I've commented the line and I still get the error
well, the error say it's something to do with the Coroutine running after the object is Destroyed. So maybe put a StopCoroutine in an OnDestroy method
@deft jungle Why did you do this?
try
{
matrix.GetComponent<Enemy>().abc = this.TopPatrolPoints[0]; ;
} catch(System.Exception e) {
Debug.LogWarning(e.Message);
}
note you have one ; too many
Hi
I'm the other guy working on that game, came in to see what can be done
wut
The one Darthspartan is seeking help for
so explain the try catch
I'd personally pick a more specific one, though I haven't set this one up
well i gotta setup the project completely again right?
the way I left it the script all this runs in was used for an entirely different thing, hence the Destroy(this);
not really you just need learn a few things cinemachine specific
locking z sometimes is just as simple as locking the target
abc is Transform ans I check whether I can set a Transform type variable from here, this works: Debug.Log(this.TopPatrolPoints.Count);
this doesn't:
Debug.Log(this.TopPatrolPoints[0].position.x);
is this something I need to fix from code when instantiating a prefab that has a camera with a stack?
what it looks like normally:
thought so too haha
whatever, i'll try
are they in the same scene?
yes
what does Fix do
im not sure. Fixes it.
but the top is during play mode
after instantiating the 2nd prefab
If that is true, and you have yet to prove it, that means that TopPatrolPoints[0] is null. Which the error message kinda hints at but does not say
i'm using it for a screen space UI for a split screen game
wdym by 2 prefabs
so the prefab is the player. When there are 2 players, with the screen split, it breaks.
The UI is on the player prefab and is set to Screen Space - Camera. The camera in the stack is to render it over everything, i's an overlay camera.
@deft jungle What I dont understand is why you have a try catch block and even if it fails you carry on regardless
are they both spawning their cameras
ye
it's like it's getting "confused" on which camera to render to or something maybe
but im not sure how to fix that or if thats even a coding problem.
TopPatrolPoints[0] is not null I did a null check
where?
I've just done it
and each camera has their own stack camera?
maybe Camera priority thing, doubt it tho
ye
maybe?
I mean it's split screen so shouldn't be right
It's not in the uploaded code
maybe I'll just add it to the stack in awake and see if it fixes
does anyone know how to access those modules from c#?
that didn't work. I wonder what "output properties" it's talking about. Maybe if I could find out I could copy the values over to the overlay camera.
it must have something to do with it being split screen
public static void DrawLines(Vector3 position)
{
material.SetPass(0);
// Set transformation matrix for drawing to
// match our transform
Matrix4x4 transformationMatrix = Matrix4x4.TRS(position, Quaternion.identity, new Vector3(1, 1, 1));
GL.PushMatrix();
GL.MultMatrix(transformationMatrix);
GL.Begin(GL.LINES);
GL.Color(UnityEngine.Color.white);
foreach(GridLine line in lines)
{
GL.Vertex(line.PointA);
GL.Vertex(line.PointB);
}
GL.PopMatrix();
GL.End();
}
Any idea why setting a 4x4 TRS matrix here and then drawing isn't being drawn in the right place? However, if I do a translation matrix and translate each point it works, but that's just a lot of extra work I don't think needs done.
probably something to do with the settings on the UI camera you picked doesn't match what it expects or something
which modules are you talking about ?
do you have a link or a screenshot to your game as is?
Hello i need a small suggestion, in my game i need some way to get the current Real Time (like DateTime.now) but the problem with that is cheating ๐ฌ since someone can just change the date on his pc and fake the date.
i was thinking of using Cloud Code from UGS to take one time the realTime from a unity server, would that be fine? or is there another better way of doing it?๐ค
Fun fact when abc is int there are no errors
Instead of:
GL.PushMatrix();
GL.MultMatrix(transformationMatrix);```
I think you want:
```cs
GL.PushMatrix();
GL.LoadIdentity();
GL.MultMatrix(transformationMatrix);```
I was thinking that I should translate the matrix after calling GL.Vertex
the position I set here doesn't change the position of where I make these vertices or at least I'm guessing
yeah just use the time off a free API
no need to do cloud code and waste your free/paid tier w unity
eg: https://timeapi.io/
this one gives you 250 million request
Simple and Free Time API to get information about current time, time zones, time zone conversions and the ability to perform safe time calculations.
ty!
whoops wrong place
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Is it normal to have so much shaderlab files when uploading onto github?
did you write a bunch of shaderlab?
If not then no
my guess is your .gitignore was not set up properly
and you probably uploaded your Library folder
don't think so
It was working before
seems it's not now
ยฏ_(ใ)_/ยฏ
just look at your repo
see what's in it
After making a new scene :/
where would I put the .gitignore file?
at the project root
but you need to do this first:
just look at your repo
see what's in it
yeh
oh ok, thanks
PlayerPrefs aren't loading in my Awake() function when i load a scene, how do i fix?
what do you mean by "aren't loading"?
i want the player to teleport to somewhere when the scenes loaded
i use a simple system to check what checkpoint player is to be teleported
first did you check if you can teleport to a location without Loading, to narrow down that issue first
no
ok so what debugging steps have you taken and what did you learn from it?
i've tried using different functions like Start()
forget the Playerprefs for a second, are you able to teleport to new location say.. in the Start method.
like
mything.transform.position = newposition
you want to make sure that works first, then move onto saving / loading
nvm i fixed issue
ok what was it?
Does anyone know why the code in the void Setup would not be working?
its not obvious? ๐
working would be you actually calling the method
So I would have to call the setup thing?
methods don't call themselves
but Update does?
There is a very specific set of methods that will be executed by Unity in various situations
Technicially Editor related but wasn't sure if my question was generic enough to slide in here, VS is telling me my second return is unreachable code? I'm trying to make this editor related function safe to reference in non editor scripts
public static IEnumerable<ValueDropdownItem> GetScriptableObjects(Type type)
{
#if (UNITY_EDITOR)
List<ValueDropdownItem> newScriptableObjects = new List<ValueDropdownItem>();
IEnumerable<ValueDropdownItem> scriptableObjects;
scriptableObjects = UnityEditor.AssetDatabase.FindAssets("t:ScriptableObject")
.Select(x => UnityEditor.AssetDatabase.GUIDToAssetPath(x))
.Select(x => new ValueDropdownItem(x, UnityEditor.AssetDatabase.LoadAssetAtPath<ScriptableObject>(x)));
foreach (ValueDropdownItem item in scriptableObjects)
{
if (item.Value.GetType() == type)
newScriptableObjects.Add(item);
else if (item.Value.GetType().BaseType != null && item.Value.GetType().BaseType == type)
newScriptableObjects.Add(item);
}
return (newScriptableObjects);
#endif
return (null);
}
They are all listed here, in the "Messages" section
It sounds to me like you want to use Awake or Start.
Okay, yeah. Idk why it works for her in the tutorial video ๐ญ
Perhaps something else calls the Setup method.
it would have to be something in the same class, since it's private
Not to hijack your help but this might also be a good resource, usually you want to find a relevant function that happens in this and run your custom functions from inside one of these
https://docs.unity3d.com/Manual/ExecutionOrder.html
what tutorial is this?
yeah, this covers the most interesting ones
In this video, will be coving setting up an inventory UI in the scene. You'll learn how to add UI elements to the canvas and reference UI elements in code.
Support me on Patreon: https://www.patreon.com/jacquelynneHei
Follow me on Twitter: https://twitter.com/JacquelynneHei2
Join the Discord: https://discord.gg/e3N9mbBRhR
Cozy Farm Asset Pack:...
(along with a bunch of very useful timing information)
I'll need a timestamp.
bingo
Randomly jumped to 7:59 and found your issue, Missed a line ๐
Ohhh my gods thank you so much
I had legit just assumed it was a function like start
Hello , does anyone know how to add a material onto a meshrenderer during runtime? (Add - not change)
set the material array via .materials = or .sharedMaterials =
naturally you'll need to make an array that is one larger than the existing array and add your new material as the last element
Something like:
foreach(SkinnedMeshRenderer rend in Highlightmeshes)
{
Material mat = rend.material;
rend.materials = new Material[2];
rend.materials[0] = mat;
rend.materials[1] = HighlightMaterial;
}
?
the foreach loop seems irrelevant as that would be for multiple renderers
more like - get the existing array
make an array that is one larger
put your material at the end of the new array
write the new array back
btw no this syntax will definitely not work, and in fact will just create a bunch of wasted memory for no reason
The unit is modular , so theres 6 skinmeshrenders on one creature , thats why that is there.
And no this didnt work
I told you it wouldn't work
you didn't do it properly
you need something like this:
Material[] mats = rend.materials;
Array.Resize(ref mats, mats.Length + 1);
mats[^1] = HighlightMaterial;
rend.materials = mats;```
Alright so... Get - resize - set.
Gotcha , lets see this in action
Voila , worked wonders
Thank you very much
you specifically can't do rend.materials[0] = mat; because rend.materials returns a fresh copy of the array every time you call it
so not only is it very wasteful - it doesn't do anything
Ahh gotcha. So i wasnt doing much with my first attempt
Is that the case with all get/set?
For future cases
Not generally. I guess most things aren't returning arrays, though.
In C#? No - C# properties can do whatever they want including creating new objects, returningexisting objects, etc
It's the case for MANY array properties in Unity though
because they often are copying data over from the C++ side
Ohh so they are being cautious on this particular thing ?
I mean, there's no way you could do that without using unsafe code
(like, literally using an unsafe block)
Check the docs https://docs.unity3d.com/ScriptReference/Renderer-materials.html
Note that like all arrays returned by Unity, this returns a copy of materials array. If you want to change some materials in it, get the value, change an entry and set materials back.
Almost everything on a unity object that looks like a field is really a property
This comes up a lot more often with stuff like this
hey, sorry for the late reply, yea
https://orikalin.itch.io/project-kobolds-tale
transform.position.y += 1;
This does not work because transform.position is a property that returns a vector3
so you'd be setting the y value of the returned struct, which is useless
Yeah it says it right there in the docs , i really should read those more when i get stuck
It's not intuitive, but now you know :p
Well you learn something new everyday ๐ , Thank you both
Is there an easy way to save the values in a component I modify during play back to editor?
copy the component from the inspector, then paste it after you exit the game . . .
but I may modify like 30 different gameobjects
then that won't work. why do you need to keep the changes to 30 GameObjects during runtime?
because im basically modifying a non-unity material
so I am in play to see how it looks(needed), but I want it saved after I exit
oh, well i don't know what non-unity material is or means. sounds tricky . . .
basically just treat it as a script with a bunch of publc floats inside that I wanted saved
this is pretty cool thanks
Cinemachine have a completely generic SaveDuringPlay attribute implementation that I dont inow why isnt part of the core engine by now https://github.com/Unity-Technologies/com.unity.cinemachine/blob/main/com.unity.cinemachine/Editor/SaveDuringPlay/SaveDuringPlay.cs
OOO thank you so much!!!
How to layer noise caves on top of an already existing mesh?
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Hey, how could i give unity location permissions?
just like in Android
is that possible?
Does your computer have a GPS receiver?
hmm, not really know
That was a rhetorical question
Phones know their own location because they have GPS. Computers do not.
There are online services that guess the location by IP address but that's not very accurate
oh
and another question, is there any way to see console logs once the game is builded on android?
does someone know why it show me this message when i try to see logs in my android game from computer?
hello, when we move file in our project folder from directory to another or rename them, unity will move them and re link the assets and the items used on the scene and stuffs. Is there a way to do that operation using code? Is it safe to just copy them manually using operating system's file manager? (like windows explorer)
i remember you can just install logcat in unity editor without using cmd
if you need terminal, then the logcat ui also provides a button to open terminal
Is this the right channel to ask why my autocomplete stopped working for unity stuff?
!ide probably your code editor is updated (or something else) so it stops working
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
What ide are you using?
VsCode, sorry for not specifying
Sometimes you need to restart the code extensions within unity
Edit, preferences, external tools
Regenerate project files with the right external script editor
In your case VSCode
Hmm it was already set to vscode and so the button didnt change anything
Is there a way to create a method similar to OnControllerColliderHit() but that only gets called when the Character Controller enters a collision?
I also tried installing like all the unity related extentions which didn't work lol
You don't see any apparent changes when clicking the button, internally it setups the files, maybe trying to close and open the editor again by clicking to a script?
Entering? You mean a trigger?
No change, no
I mean making a method that acts similarly to OnCollisionEnter() but for a Character Controller.
You can do something like
OnCollisionEnter(Collider other) {
if (other.TryGetComponent<CharacterController>(out var controller))
// Do stuff with controller
}
Alright thanks! I guess I'll switch to vs or try the fun links from the bot ยฏ_(ใ)_/ยฏ
If I understand correctly what you are trying to do ๐ค
I know that a friend of mine had to change from VSCode too because someday apparently the intellisense stopped working completely
So yeah ๐
Makes sense but I was wondering if we can create methods that get called the same way. For example, Update() is called once every frame but we do not have to call it anywhere in a script. Can we create methods that get called in a similar fashion?
As far as I know the only way to do that is via C# events or Unity Events. You cannot modify or create new functions inside the Physics simulation environment tho :(
So you have to stick with the OnColliderEnter / Stay / Exit
Setting a MaterialPropertyBlock works in editor runtime, but not in build (Win10), what could it be?
Debug.Log("<color=blue>" + _rendererMapper.Renderers.Length + " renderers</color> on " + transform.name + ", queued " + _shaderPropertiesToApply.Count + " properties");
foreach (var renderer in _rendererMapper.Renderers)
{
renderer.GetPropertyBlock(_propertyBlock);
foreach (var propertyToApply in _shaderPropertiesToApply)
{
Debug.Log("<color=orange>SetFloat </color> " + propertyToApply.PropertyIdentifier.PropertyName + " " + propertyToApply.ParameterValue);
_propertyBlock.SetFloat(propertyToApply.PropertyIdentifier.Hash, propertyToApply.ParameterValue);
}
Debug.Log("<color=magenta>Applied</color> MPB to " + renderer.name + ", isEmpty: " + _propertyBlock.isEmpty + ", materials: " + renderer.sharedMaterials.Length);
renderer.SetPropertyBlock(_propertyBlock);
}
The debugs seem to indicate everything's in order, how to debug it further?
Also made sure the PropertyIdentifier.Hash is correct, as it should be or it wouldn't work in editor either
@worn night Update: Apparently I had to update the Visual Studio package from the package manager
Seems illogical considering I wasn't using VS, but I'm not complaining because VS was so ugly I couldn't stand it anyways
where should i go for performance/profiler issue?
Hey guys, what's the best way to store images locally in mobile, with or without a database
If it deals with code, any of these channels. If it deals with other categories then use their respective channel. General unity issues are #๐ปโunity-talk
Hi everyone, I need your help, I have a problem when I change the scene; I currently have 2 scenes named MainMenu and Game, when I launch the scene game I don't have problem but when I start MainMenu and switch to Game a light problem appear, some warning appear with shader problem with this text: The tree TFF_Birch_Tree_01A must use the Nature/Soft Occlusion shader. Otherwise billboarding/lighting will not work correctly. but this warning appear only when I switch scene, did someone know how to resolve this problem?
I figured this out for anyone interested, I was calculating the property hash in OnValidate, since it only run in editor the hash wasn't being recalculated when running the build
Each name of shader property (for example, _MainTex or _Color) is assigned an unique integer number in Unity, that stays the same for the whole game. The numbers will not be the same between different runs of the game
logic = GameObject.FindGameObjectsWithTag("Logic").GetComponent<LogicScript>();```
the ide give me an error with ".GetComponent<LogicScript>();", why?
Can we use from clause in Unity no problem?
Please provide the actual error in #๐ปโcode-beginner
Sure,
and you'd see, yes.
i asked alredy a question in code beginner, i dont want to write over it, sorry for the error
wanted to make sure there wasn't any gotchas secretly like async lol
thanks!
Anyone know why a json save file has it's data reset sometimes when restarting my computer
How does it work to have kinematic rigidbodies that donโt just go through walls? I see a lot of people using kinematic rbs for characters, and just have to wonder: how do you make it actually โcollideโ with shit properly?
as in, not fall through floors, get pushed by walls etc
I see that I really need a big degree of control over my character, and I keep fighting the physics system with dynamic RBs. So I think I need to bite the bullet and go towards a kinematic RB
take a look at source code how they made KCC asset.
The short answer is physics casting and rays
i see. that seems like doing the physics simulation myself, right? Iโm wondering how it deals with constraints. Because if I have one block going into another block, if block1 casts to stop at block2, then block2 casts to stay put, that has a different result than the reverse order. Right?
but I guess everything finds a stable configuration in the end with no overlapping colliders?
actually, I wonder if I can replace moving transforms blindly with that cast? As in, instead of transform.Translate, I instead Cast, find distance, then move by that much.
I forget the details, its been a while..
They also have moving platforms
https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131
Thanks. I saw that before, but Iโm still thinking.
I can make one dynamic rb player ride a platform (with only a little jank).
The issue is I actually have multiple dynamic RB blocks, where blocks can ride blocks, can ride blocks, and be in each otherโs reference frames, which is when it breaks. Because Iโm moving transforms.
Iโll need to check KCC again. ty
Maybe one more thing that might help: Is there a way to do casts that only search for compatible force receive layers? I have overrides, and I could check manually, but there are some cases where my framerate would be crippled if I have a Cast that returns a bunch of colliders from which we donโt receive force
anyway, ty for replying. I've been struggling to get any help on this problem for a while. Appreciate it.
No problem!
Goodluck with your project ๐
Ugh, I finally figured out why my guy would stop taking damage if he wasn't moving. His rigidbody kept sleeping on the job.
The shader problem is unrelated. This is just a lighting issue.
When you launch a scene directly in the editor, it'll generate some stuff automatically
this won't happen when you load a scene
You need to bake lighting in the scene. See here #๐ปโunity-talk message
Ok i gonna check, thx for the reply
How can I make a Kinematic Rigidbody "push" a Character Controller?
By using spatial queries like raycasts, overlaps, or something and coding it yourself
Oh, raycasts. Sounds performance heavy.
raycasts are not performance heavy.
But if you want that kind of behavior you're better off using a Rigidbody controller
otherwise you'll have to do all the physics yourself
I did it up until now. My character scripts are almost complete.
I only have a few thing left to deal with, amongst which there's this issue.
I have some interactive objects on the map(doors and elevators, mainly) and I want them to be able to move the character.
it work perfectly, thx you โค๏ธ
is this where i ask about testing?
i didn't find a specific channel for it
i'll ask anyway, is there a way to add the assemblycsharp dll to a test so i can reference it?
i've been looking around and it seems testing is hard ?
at least preparing and referencing them
if you have scripts in different folders, you have to reference everything separately
and you can't reference assembly csharp
even if you create an assembly definition in the asset folder, it doesn't reference the scripts in subfolders
even if you reference your local scripts, if those scripts reference something like textmeshpro or unity.localization, you'll get a lot of errors because they're not referenced for some reason
if you want the easy option you can just throw the tests in an Editor folder without an asmdef i think? you don't need to create a test assembly
then they'll be included in the Assembly-Csharp-Editor dll and you won't need to set up any references
how about play mode tests?
yeah you do need a test assembly for those
i can create a regular nunit project and reference the assembly csharp project normally
maybe play mode needs you to create an assembly for script in different folders? i don't get it
yes if you need to reference game code i think you'd have to make an assembly definition for that and reference it
does Start() just wait for all pending Awake calls to be resolved?
don't think start waits for anything related to other scripts
afaik they all run independently
eg, 2 scripts with Update never Update at same time
but if I instantiate a prefab, all of its components call Awake, then OnEnable, then Start, right?
so one component's Start won't get called while we are waiting for all the other components to get their awake? I think?
i think they only follow their execution order and don't care about other components
I'm not sure that makes sense, because then Start can get run to reference something that isn't initialized yet, right?
isnt that what happens though most of the time you put init code in Start?
thats why Awake is better cause it happens on all scripts before they run their own start
i think depending on also if object is active first or not
Hey, so, I am making a game like "Scrap Mechanic", where you can connect objects and make "circuits", but, I don't really know how to make an "overlap" effect on the objects, like it happens on the game
(in the image, orange and green circles)
How can I make an approach to that effect?
could be anything tbh.
sprites + line renderer
or drawn meshes ?
or graphics lib..
since they have 3D to them I'm gonna guess meshes
it can be replicated though fairly easy
it don't really matter, but, I want to place the circle on the middle of the object and be able to see it from any angle (it will be inside)
it would be like a gizmo
a circle or cylinder ?
the image you shown has disk shape / cylinders
can be any of them
just for showing them it's enough
sorry for don't explaining much XD
ideally you want to use a material you can see above any other objects
yeah
yeah, it's exactly what i want
all you need to do is spawn that object / disk shape to where your points are
thank you :D
is using a foreach loop in a if statement that is checked every frame a bad idea for performance and shit?
The code:
if (MusicSpeaker.time >= (Notes[CurrentTimeStampIndex].SpawnTime - timeToReachTarget) + (NoteSpawnOffset / 1000))
{
//it only checks the first one instead of progressing
Debug.Log("[GAME DEBUG] Game should create a note, before this event, and remove it from the list");
foreach (Tracks track in TrackedTracks)
{
if (track.TrackID == Notes[CurrentTimeStampIndex].Track)
{
Tracks[Notes[CurrentTimeStampIndex].Track].SpawnBeat(Notes[CurrentTimeStampIndex]);
}
}
CurrentTimeStampIndex++;
}
Start() wait all Awake() and OnEnable() but only for script activate, unity go like this Awake -> OnEnable() -> other Awake ..... but if you want you can change the script order in Script Execution Order in the Project Settings if you need one awake before another one
thatโs good to know. I was mostly wondering about instantiation. Like, if I do;
Instantiate(PrefabWithComponent1);
doSomething with Component1;
Like, in the same line. Would Component1.Start() be done by the time I hit that second line?
If you do something like
thing.DoSomething();```
It's possible that `Start` didn't get called in between (I don't know about `Awake` but I think that one should always run)
That's something I've encountered in my current project, but I solved it easily by calling my own Initialize method before DoStuff, I'm trying to avoid relying on Awake/Start/OnEnable etc as much as possible
Awake and OnEnable definitely are done
wasnโt sure about start
OnEnable is weirdly fast as fuck
I also use an Initialize method sometimes, when I need the intermediate speed
Using a wrapper class to run edge-playback using windows natural voices. Does microsoft have any libraries for tts that use the natural narrator? Else I'll need to use mpv with edge-playback through wrappers which is awful
What I'm doing is something like that
[SerializeField] private bool _AutoInitialize;
private void Start()
{
if (!_AutoInitialize) return;
Initialize();
}
public void Initialize()
{
...
}
That way, the stuff that gets spawned dynamically will have it's Initialize called by some other Script, but if I want to quickly test some functionality I can drag and drop a Prefab and tick AutoInit
I know microsoft has speechSynthesis but that is the default narrator
I need to know if there's a win11 library for the natural narrator
maybe I should use an IInitialize() interface. All my entities have a spawnedEntityHandler, which I could use to just GetComponents<IInitializable>(), then initialize them all. That might work for me.
I donโt actually know about TTS, but bump so this doesnโt get burried by our convo.
no problem
That would be a possibility, or you could put an Initialize method into the Entities base class to avoid having a GetComponent call
If someone could please take a look at this i'm desperate : https://forum.unity.com/threads/generated-input-action-class-randomly-stopped-sending-callbacks.1506035/#post-9408860
Is it possible to disable eventsystem to disable UI buttons and then enable eventsystem?
Why not use the .interactable property of the button to disable it instead?
Okay, to be honest, I'm modding the game and I have a problem: when the UI is turned on, my custom UI works, and when the game's UI is turned off, it doesn't work, do you know why?
its something with InputSystem/EventSystem
If you disabled the event system, UI isn't going to work
Awake and OnEnable both instantly execute
assuming the game object you're instantiating is active, and that the component is active and enabled, respectively
the problem is that the game somehow disabling the UI interaction when its not used
and uh
that making a big problem
Start will not run until the next frame.
for (int i = 0; i < fishes.Length; i++)
{
var randTarget = positions[Random.Range(0, positions.Count)];
var routine = StartCoroutine(MoveFish(fishes[i], randTarget));
fishesInCoroutine.Add(fishes[i], routine); // dictionary <Fish, Coroutine>```
Is this the right way to do this with coroutines ? It's not working for some reason not stopping
public void StopMovingFish(Fish fish)
{
Debug.Log(fish.name);
Debug.Log(fishesInCoroutine[fish]);
StopCoroutine(fishesInCoroutine[fish]);
}```
what if you start moving twice?
yout StartCoroutine/StopCoroutine syntax is correct. But are you sure you're calling it on the right coroutine? Are you sure it's the right Fish?
you'll get an exception on the second attempt to call Add in that case
I'm not sure, how would I check ? ๐ญ
wdym ?
maybe print the instance ID?
the code ontop is in Start currently
your code would start throwing errors after one round of moving fish -> stop moving fish
ah, okay
you should make sure you're stopping different fish each time, then
just tested..its not even stopping any other coroutine on any fish sadly, idk how to check if coroutine is the right ones :\
I normally just make all the fishes control their own movement but tried to make something else do it now all hell broke lose with managing coroutines lol
I don't see any reason for it to fail when just looking at that code
so I'd need to see more context
thats whats making me ๐ตโ๐ซ
the fish appear to be moving many times
not just once
so are you starting a new coroutine after reaching the target?
if so, your original coroutine is now irrelevant
wait..
possible..
well what does MoveFish do
hence why i wanted to see code
Ahh shit I think its this
private void FishDestReached(Fish fish)
{
StartMovingFish(fish);
}
why not just put a loop inside the coroutine
which is a separate mechanism entirely from how you do it in Start
here is my whole func
IEnumerator MoveFish(Fish fish, Vector3 target)
{
while (Vector3.Distance(fish.transform.position, target) > 0.1f)
{
float T = 2 * Time.deltaTime;
fish.transform.position = Vector3.MoveTowards(fish.transform.position, target, T);
var dir = (target - fish.transform.position).normalized;
if (dir != Vector3.zero)
{
Quaternion targetRotation = Quaternion.LookRotation(dir);
fish.transform.rotation = Quaternion.Slerp(fish.transform.rotation, targetRotation, 2 * Time.deltaTime);
}
yield return null;
}
FishDestReached(fish);
yield return null;
}```
dont mind the bad lerp plz
just testing
instead of restarting the coroutine at the end, put another loop in
so it continues forever
yes
or, at least, make sure that FishDestReached updates the coroutine dictionary
I'd just make Start call StartMovingFish and then make StartMovingFish correctly track the coroutine
oh so like 2 while loops?
while (true) {
while (fish is not at its target) {
MoveTowardsTarget();
}
PickANewTarget();
}
ahh thats clean
or if you want to be funny: yield return MoveFish(fish, PickTarget());
you can yield another IEnumerator
this returns same one ?
if you yield an IEnumerator, unity will call MoveNext on it every frame (or based on what you yield return from it) until it's exhausted, then resume calling MoveNext on you
I don't think it'd be very intuitive here, though.
It's a neat way to "compose" several iterators
I think i accidentally done that pattern before in the past
you can also yield return literally whatever you want and unity won't complain
yield return "hi"
slowly got less afraid of while loops after doing console rpg :p
while loops everywhere
I heavily used enumerators to create abilities in an RTS
I haven't nested them too much though
I only used IEnumerator in unity ๐ญ
just found out about IAsyncEnumerable a few days ago
IEnumerator<T> is the generic flavor of that
so an ability might be a method returning IEnumerator<AbilityStatus>
it could indicate that it's busy or that it failed
oh that actually makes lot of sense , should've picked them up earlier
IEnumerator just yields object
which part of it did unity change just the yeild types?
well, you can yield anything you want from an IEnumerator
Unity uses non-generic enumerators in several places
I don't think you could even create a type that meaningfully covers all of the things you can yield for a coroutine
C# does not have union types (booooooooo)
Transform produces an IEnumerator instead of an IEnumerator<Transform>, which is annoying.
is that why you can do foreach on it ?
I found out how to fix it, just use AssignDefaultActions and it works, probably the stupidest way but it works
yeah -- you have to explicitly state the type you want, or else you just get object
foreach (var thing in transform)
thing will be object
foreach just checks whether what you pass to it has a GetEnumerator() method
yeah
I don't think it even cares about implementing the interface
It's just a little โจ language magic โจ
haha remember this mistake once
i make that mistake like every single time i iterate over a transform lmao. every time i'm like "why isn't this working. . . oh right, i have to specify Transform"
habit for me almost always writing var
i usually just forget that i can do that and do a for loop
dodged!
then I write this and my game crashes
lol
Does anyone know what this error is referring to? It doesn't seem to be doing anything, but it just started showing up and I can't figure out what's causing it. It pops up now every time that I save a script.
it's just an editor error likely due to something happening in a window that uses the graph editor like the shader graph or animator. you can ignore it as it won't affect the game
I'd just give the editor a restart.
ok sounds good
Hey has anyone found a good solution for intellisense of some kind for writing shaders in visual studio?
or is there a way to use both VScode and VS with unity? (so I can open shader files in VScode and cs files in VS)
afaik there is no way to change default editor for shader files only , in unity.
I also open my shader code in VSCode, for some reason VS corrupts them for me
there might be an extension for some type of syntax helper
yeah i only found extensions for older VS versions
i like 2022
how do u open in VScode?
from editor or from explrer?
i rightclick the shader and Show in explorer then open from there
the only workaround i know ๐ญ
thank you lol. do u have any extensions to help with intellisense in VScode?
I dont have specific ones, you can try looking here
https://marketplace.visualstudio.com/search?term=HLSL&target=VSCode&category=Programming Languages&sortBy=Relevance
I dont write the code sorry lol that stuff I paste from the net
I usually have shadergraph for my own stuff
also does unity still recompile automatically on save If I edit in VScode?
okay thank you haha
iirc it does



