#archived-code-general
1 messages · Page 48 of 1
it should do yeah
I have no idea why it's not incrementing the second time I press Jump but for the rest it will
1st Press: Counter = 1
2nd Press Counter = 1
3rd Press: Counter = 2
4th Press: Counter = 3
@hollow stone Wait, I think it's possible that my spherecast is hitting my own player. If I put my player on it's own layer and exclude it from what you are allowed to grapple on to, would that prevent the spherecast from hitting my own player?
what are you using to input for jump?
spacebar
did u try testing that on its own to see if it was the problem?
Should do
Thanks I'll try it
@hollow stone Yay it worked! Thanks so much
It can't be since the the log gets outputted each time I press space
oh my b
that is so weird
the error is prrobably coming from somewhere else then
maybe you have something somewhere modifiying a public variable that it is not supposed to modfiy
that wouldnt really make sense tho since its all in 1 method
yeah
That's the only place it's been modified
wait no I'm wrong
when the player is grounded the index is set back to 0
During the jump the raycast is still hitting the ground and sets it back to 0 I bet
hey guys i am struggling so hard setting up a database in unity does anyone have some suggestions? I tried mysql but the app for it was to much so i switched to firebase got around with the website easily but anytime i go to write code for auth functions it keeps saying my app is not found and ive re downloaded the sdk have the auth installed and my json for google
How do people make thumbnails from images on a device? Because it seems like reading the entire image file is overkill when it's a large image and I only need a small sized graphic for the thumbnail.
I'm making a UI for selecting images from a camera roll
!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.
Trying to RSA encrypt with a key generated from openSSL in php.
byte[] base64Bytes = Convert.FromBase64String("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4Q9oqSbWLu779TLQNkvd GRzzKhHtkZcJecz7N0E9RzwhqWztS5wnTzZMZGZRVzB/5hhZSh+U4xBnSbfs/y7q vC9kzzP2yZR5qwlWUjy3iPgtWtn7DbFZ8gdkVrTcubg9HC7TFtDcAE0DVg8jefFq 1eowQhkJgdEyyGORS1DO+fmhhciV/ahD/m3DiIWwNTvjllTHCqNSHEnR0SQO4hb5 HAEIf8kYNLtUCmboX7ZAKTY2+PyRMSRtN3cYEw91LUPu1Xcq0XPI3l1LfswdjaFB XKvFEgv/kzP7c2EYr3i5JvQKe4MFW5H9PxwEUQ7idwifGb0BICcKY+rdZTNchSq4 AwIDAQAB");
CSP.ImportRSAPublicKey(base64Bytes, out int bytesReadd);```
Gives me an "Operation is not supported on this platform." error.
I'm on .net standard 2.1 and the docs even state that it targets that framework
For whatever reason, when I call <mesh>.submeshCount I'm getting 1 instead of the 12 listed here?
how can I have a raycast interact with the canvas?
Can you explain what you need in plain terms?
Im trying to make a setting in my game where I can drag and drop ui elements to allow my players to customize the hud in the way they want it to look, so I am using a mousepointtoray but it doesnt detect ui elements, is there a way to allow that?
typically you'd use camera.Main.ScreenPointToRay(Input.MousePosition) to draw a ray from your camera into the 3d space calculated by your mouse position.
also make sure to check into the drag/drop handers, IPointerDragHandler and it's sublings.
okay thank you
I have a script which lets me drag objects with the script attached around in a grid-like fashion where they snap to coordinates of a particular "cell size" increment. heres the code https://hatebin.com/nalqhcnupz - unfortunately, this has an issue where every time I adjust the location of an object, it comes closer and closer to the camera, and theres no way to move it "backwards" to where it originally started. Does anyone have any suggestions for how I could go about fixing this? either a video showcasing an alternative system or some way I can manipulate the camera to avoid this little issue altogether? Any help appreciated, thanks
Okay, got a solution working!
using System.Runtime.CompilerServices;
using System;
namespace EffortStar {
public class RuntimeCache<TKey, TValue>
where TKey : class
where TValue : class
{
ConditionalWeakTable<TKey, TValue> _table = new();
Func<TKey, TValue> _calculate;
public RuntimeCache(Func<TKey, TValue> calculate) {
_calculate = calculate;
}
public TValue Get(TKey key) {
if (!_table.TryGetValue(key, out var result)) {
result = _calculate(key);
_table.Add(key, result);
}
return result;
}
public void Clear() => _table.Clear();
}
}
using UnityEngine;
namespace EffortStar {
public static class AimInfoCache {
public static readonly RuntimeCache<AttackActionConfig, AimInfo> Cache = new(GenerateAimInfo);
#pragma warning disable IDE0051
[RuntimeInitializeOnLoadMethod]
static void Initialize() => Cache?.Clear();
#pragma warning restore IDE0051
static AimInfo GenerateAimInfo(AttackActionConfig config) =>
config.CalculateAimInfo();
}
}
Simple enough I guess, and prevents any unwanted changes persisting between runs.
Any idea why my player controller (in the bottom left) has its movement and rotation thingy in the top right?
is NavMeshAgent.SetDestination() effect your performance? Like if I set a new destination every frame vs every second will it make any difference?
You have your tool handle position set to Center instead of Pivot
bump
thanks
hello, i must apologize if this is not the correct channel for this to post, but i need a ps3 webcam driver from github updated to support multiple cameras at the same time (very urgently)
if anyone knows how to implement this or by attempt, please write me
@ me
erm how do I set the material of a mesh at runtime? I'm calling mesh.materials[i] = myMaterial but it doesn't seem to change the default value
mesh.material = MyMaterial works for the first entry in the list; but does not work when I use the indexed reference.
copy to temp array, change the material in the temp array, assign it back to the mesh
Are there any downsides to using the Enabled flag on scripts that don't update but I'd like to be able to turn on and off? They're reacting to other game events.
is there a particular reason you are offsetting the Z position?
and "theres no way to move it "backwards" to where it originally started" isn't exactly accurate
but perhaps your code right now doesn't allow for it
just tryna debug
I have an Object instance, Most things I assign to it are Monobehabiors/components, as I need the GameObject reference they are on so I cast them to Component, but I tried to put a GameObject as the Object and I am getting a cast exception. Is there something else I can cast Object to that would allow me to get the GameObject it is related to(aka itself if it is a GameObject)?
I mean I think GameObject would be the only thing not supported that could be assigned from editor so I can do a check for it.
how do i prevent child objects from being scaled when i scale the parent
either don't make it a child or scale it the opposite way
i created separate thread for long math operation, but when it gets run, unity still freezes...
how can i do it so it doesnt freeze during the math calculation?
well for one you probably cannot use GetComponent on a separate thread so that likely wouldn't work correctly anyway. but also are you certain this is even the code causing the freeze?
for jumping Im using add force but its super inconsistent with the amount of force idk if its because i press the space bar multiple times during the jump or what
what is the best workaround or should i just set the velocity
you'd have to share the code for anyone to be able to tell what you are doing incorrectly
okay well for one, i'd recommend just calling the IsGrounded method once per Update rather than twice, there's literally no reason to call it more than once. but it is possible that you are being considered grounded for one or more frames after applying the force. What I normally do is I only check for ground when Y velocity is at or below a certain threshold, then reset the grounded state to false as soon as i jump so that it doesn't start checking for ground again until the object has started descending from its jump
also if you just want a single impulse of force you should consider using GetKeyDown instead of GetKey, this will also help prevent the object from applying the impulse force for multiple frames in a row
using Input.GetKey in Update will mean it is executed multiple times inside the physics loop
thanks it works much better now
Is there a better way to get component of a triggered object, instead of using getcomponent in OnTriggerEnter()
??
TryGetComponent in OnTriggerEnter
But won't it run like every frame?
no? OnTriggerEnter only happens when an object initially enters the trigger
even if that were the case, how else would you expect to get a component if all you are given is a reference to a Collider?
Yeah..i thought there's a different way which I don't know of
how does this work?
i tried to use it but i couldnt get it to trigger
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-activeSceneChanged.html
it is an event that you subscribe to. do you know how events work?
yeah, i added the event from basic c# class with [InitializeOnLoad] and added a test method to it in its constructor
it logged that it should have added the method to the event but it never logged that it triggered
show the relevant code
hold on let me find it
also are you certain you don't want to be using either RuntimeInitializeOnLoad (since the event you are subscribing to is only invoked during Play mode or in a build) or using the editor version of the event instead?
oh, that might be an good idea
oh ok i will delete that and put it outside
though can i use Debug.Log() or print() in threads or these not too?
looks like i dont have the code on my laptop but i can rewrite it real quick its just a couple of lines
you can certainly try. but most of the unity API is not thread safe, a lot of it will even throw an error if you try to call it from another thread (or will just stop the thread if you aren't correctly handling your errors)
i believe it was something similar to this
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEditor;
using UnityEditor.SceneManagement;
[InitializeOnLoad]
public static class SceneChangeDetector
{
private static Scene _previousScene;
SceneChangeDetector()
{
_previousScene = EditorSceneManager.GetActiveScene();
EditorSceneManager.activeSceneChanged += onSceneChanged;
Debug.Log("Added to event");
}
static void onSceneChanged(Scene previousScene, Scene newScene)
{
Debug.Log("Trigger");
}
}
why not wait until you have access to the actual code to ask for help? then you can get help that won't require guessing at what the issue is
should i use a raycast or bullets with colliders for guns
i guess i can come back later when so i know for sure 
How do I change the layer in an object like this?
Sorting Layer.
In what order do Scene GUI Handles get drawn?
If I draw 2 handles in the same location
Which one comes on top
How do I control it?
I'm talking 2D, so I think I can change the Z position
I remember Unity Editor has built in API to open explorer so you could choose a specific folder. Anyone remembers what is it's name?
Or one of the variants in the EditorUtility class? There are several depending on where/what youre looking for.
yeah
Hi.
I have a prefab that contains a certain amount of tagged objects.
Is there a way to count those objects on Scene launch prior to initializing any instances of that prefab?
sure just iterate over all the prefab's children
and count
Oh, I didn't think it would be that easy.
Thanks!
Using NavMesh, is possible to add path restrictions to specific agents (not specific agent types, but specific instances of an agent)?
I would like for example: to disallow a specific agent from getting outside some rectangle(s).
You can give the navmeshagent an area mask.
Then you need to give all the rectacles an area type.
All explained here: https://docs.unity3d.com/Manual/nav-AreasAndCosts.html
Does anyone know how to set a position of a grid with a vector3int?
anyone know how to make a box collider hide all entities that enter it, but reveal those entities if the player also enters it? ChatGPT wrote an OK little script
Yes
how would I approach this?
Show what you have attempted?
With a grid do you mean some sort of array or some grid component?
GridLayout?
Does anyone have an idea why I'm able to instantiate the gameobject, but as soon as I try to add it to the list, I get NullReferenceException? I have no idea what could even try to figure it out
...
static public List<GameObject> level;
void PlaceItemOnScreen(Vector3 mousePosition)
{
...
GameObject gameObject = SelectedItem.selectedPrefab;
gameObject.transform.position = prefabPosition;
Instantiate(gameObject);
level.Add(gameObject);
}
the prefab gets instantiated as expected, it appears on my screen, but as soon as it tried to add to the list it errors
Given your story I would think a static List doesn't get serialized by default and you did not initialize the list yourself.
one sec
so this is just the part of the code that refers to the generation of terrain
what I am trying to do is
move the grid that generates the terrain via code
in the line
Vector3Int SpawnHere = new Vector3Int((int)SetGridPosition.transform.position.x, (int)SetGridPosition.transform.position.y, 0);
SetGridPosition is a gameobject that I assign a cube to that will make the grid active once the player has entered into the trigger box
the problem I am having is
You can type full sentences btw
Move it where? The question isn't very clear
The GridLayout component is probably a good choice if you want to do conversions
Or anything grid based
SetGridPosition is where I want the grid to be moved to
I am trying to do it via code so that it can be randomly generated in the world as the player progresses
GridLayout can be used with code
I havent used it yet but if you look it has useful functions for converting local to world coordinates etc
https://docs.unity3d.com/ScriptReference/GridLayout.html
Loop the grid array and add the offset to each position
Calculate the offset with SetGridPosition.position - pivotPos where pivotPos can be your first grid position or whatever you want
hmmm ok I'll take a look into it thanks 😄
here is what I attempted
using UnityEngine;
public class HideObjectsInCollider : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
foreach (Transform child in transform)
{
child.gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");
}
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player")
{
foreach (Transform child in transform)
{
child.gameObject.layer = LayerMask.NameToLayer("HiddenObjects");
}
}
}
}
@hexed pecan what do you think?
Do you mean to just hide them or disable them?
Also what object is this script on, is it the one that other objects enter?
Why would it hide its own children? Im confused
i have this interactive (mini) map i built and now i wanna draw more information as text into the scene. whats the proper way to have text anchored to 3d objects?
i read you can make a canvas and glue that to the object, but i smell that this might be overkill?
Just child it to the object
well i dont care about the canvas. i just want to anchor a bunch (20+) texts to different transforms
Is it for debugging or final stuff?
final
oh, then just child it
But you'll probably want to make sure the text always faces the player
so attach a canvas with a UI text to each object?
afaik UI texts need a canvas to work
You can use the 3D textmeshpro object as well, no need for a canvas.
cool thanks 👍
Also I have a question
If in a game I have a bunch of items that I might want to add to later in some update
How would I take care of that list
like if I had a list of swords somewhere with sword1, sword2, sword3
But I added a sword4
How would I make sure that gets added to the list of swords so that I can iterate over the list to show in a menu later or smth
And how would I even add the sword?
Where does that list live?
Would it be an addressable asset that I push in an update or smth?
I haven't made any of this yet lol
This is just a problem I suddenly thought of, since I've never considered stuff like updates to a game after release
I guess.... would it make sense for the list to live in a scriptable object?
But then I would need access to the sword prefabs for instantiation at some point, so maybe it'd have to be a monobehaviour?
I guess I could have it be a scriptable object or smth, and then match the string of sword list and the prefab names and then something else in game could instantiate from resources
It could be an SO as well, that's how I personally store this type of lists. As for the updating/adressables question, no idea
You could just reference the SO asset that has the list and get the prefab reference from there. No need for Resources.Load or anything
Yeah, but I'm worried about how live updates would affect everything I guess
But I don't know how those work at all
Maybe that's what I should study next
cool the TextMeshPro was exactly what i wanted.
cant believe how obsolete my "central canvas that imperatively positions UI images to screenpos of worldobjets" was
Henlo to you too
lol I mean, sometimes the worldtoscreenpos is useful if you just want the icons to all be the same size on the canvas and such
i even resized the canvas images to simulate 3d space size differences 
How sus is a singleton that tracks state?
uh depends. in my old project, the GameServer and GameClient were Singeltons
I don't know anything about multiplayer or servers yet
(hoping to delay that since I know it will be very hard)
Well it's a status effect manager that can take a generic status type and matching enum to add a status from a list of prefabs to the specified unit
I figure I'll end up using FindObjectOfType on it most of the time anyway
How often do you guys use FindObjectOfType (or equivalent) ?
if its a singleton, you dont need to find it tho.
just give it a public static MyClass instance
oh and it keeps track of every status on every unit
i try to avoid anything like Find. never use it.
but im not a gamedeveloper and not used to even have the ability to search for instances by class
if you're drawing little text labels that you purposefully want to be legible, it will be easier to place the labels on a canvas and translate world space to screen space to position them
if it isn't important that they are legible, you can put the text meshes in world space
I'm using it a lot when implementing particular derived classes that implement and handle their own implementations - they find the classes they need and call the methods they want
it is also sometimes, but rarely, expensive to render another camera. make sure your camera is configured correctly by putting all this stuff on a layer, and turning off unused features
But then I think, if I'm using Find like this maybe I might as well make some of these managers singletons...
But THEN I think, well if this is my thought process I'll just end up making every manager a singleton, and that can't be right
my former roommate did a unity project for his bachelor, and had almost no coding experience. so instead of properly managing a tree of references, he just had a ton of scripts and objects floating around somewhere and used search everytime.
THAT was a codesmell
a lot of managers are singletons by nature, doesnt mean you have to build them as such
I think my architecture is pretty good. But it's not like I get any feedback on it so who knows
also its kinda pointless to hand down a reference to your WorldManager or whatever into every single tiny object.
a public static getInstance() is much better
K I'll just make it singleton. Might as well learn by doing
hence why DI is used for stuff like this but for some reason nobody in game dev which is making a client uses DI
whats DI
hello can somebody help me
dependency injection library
DI?
It autowires the dependencies
I heard from professional game devs that DI in gamedev is pretty pointless
.e.g.
Lets say you had
MyComponent(MyMenuManager manager)
It will autowire inside the object
hello can somebody help me
so u dont need to deal with the object lifetime
ask ur question dont ask if someone can help u
THIS IS A HELP CHANNEL
DI is pretty nice for decoupling logic
So you're saying DI should be used more than it is?
its not used at all unfortunately
in every part of software development we generally use DI
to wire up constructor dependencies
You can use stuff like myDiContainer.AddSingleton<MenuManager>()
then it'll automatically resolve it
when myDiCotainer.Dispose is called it disposes all the services
not a fan of dependency injection mostly. it hides a lot of things and makes understanding stuff more difficult.
still has its usages oc
So u dont have to handle the lifetime
the beauty of the DI is u dont have to handle construction or lifetime of the object
I would need to see an example to understand
tbf nothing that the client uses
for some reason people dont use DI in game clients
When I was learning to code (explicitly for purposes of game dev) I spent like two weeks trying to understand DI, not really succeeding, and then never using it anyway after hearing some gamedev pros trash talk it in gamedev context
for game servers its a differen story 🙂
In enterprise DI is used for nearly every large application
except in the gaming industry for game clients.
better examples
What are the kinds of situations where you start thinking about using DI?
When you have a huge amount of dependencies in your services which can change, or when you have dependencies and you dont want to manage their lifetimes and creation yourself
if im using unity on Linux, is it recommended to use vs code? if not, what other alternatives do you guys suggest
"dependencies which can change" as in a class depends on a certain class at one time, and a different class at a later time?
VSC works well on linux (for my work, dont know about unity)
.e.g.
MyConstructor(MyDependency dep) {
}
MyDependency(AnotherDependency1 dep1, AnotherDependency2 dep2) {
}
Now normally without DI i will need to do:
new MyConstructor(new MyDependency(new AnotherDep1(), new AnotherDep2()))
With DI you can just do:
serverProvider.GetComponent<MyConstructor>()
It will new up the objects automatically
and handle them
ofc u need to register them .e.g.
serviceProvider.AddSingleton<AnotherDependency1>();
serviceProvider.AddSingleton<AnotherDependency2>();
serviceProvider.AddSingleton<MyConstructor>();
Jetbrains Rider is the best IDE afaik, but vscode is fine
you can see the benefits right here.
yes, so imagine you had a interface called
IFileSystem.
Now in the DI
You can register the interface like this:
serviceProvider.AddSingleton<IFileSystem, PhysicalFileSystem>();
or if you had another impl of IFileSYstem you can change it to something like this:
serviceProvider.AddSingleton<IFileSystem, CloudPhysicalFileSystem>();
Ability to easily change out deps is a nice one
now whenever you reference IFileSystem in a constructor it will automatically resolve the correct one registered in the DI
okay
hello can somebody help me
dude just ask your question
how do i fix this problem
looks like your code editor is set to something wierd (at least thats suggested in the error)
check edit>preferences> external tools
no
do i need to have visual studio
Hey guys so im making an fps and im making a big room for a level but for some reasonwhen the walls are are the walls do this bc of the camera.how can i fix?
yeah sorry
Make sure that font supports the characters too
no you can use any IDE you want. generally Visual Studio is a good starting point if you dont know what you are doing
either is fine. The script I posted would be attached to the collider. It's to hide enemies, other players, and objects on 2nd and nth floors of buildings while the player is on the lower floors in a top down game. The approach was to have a tag or layer for hidden objects and add and remove objects from that tag or layer as they enter or exit the trigger. Maybe there is a better way?
Well the script is hiding/showing its own children instead of the one its colliding with, so I'm not even sure if it works correctly
that's probably why it doesn't work or do anything
because it can't parent itself to objects dynamically... How can I make it so that it works on collision / trigger enter and exit
how do i get IDE
An integrated development environment (IDE) is a software application that provides comprehensive facilities to computer programmers for software development. An IDE normally consists of at least a source code editor, build automation tools, and a debugger. Some IDEs, such as NetBeans and Eclipse, contain the necessary compiler, interpreter, or ...
how do I install
You install visual studio either manually from the website or through Unity Hub.
Instructions for configuring it are in #854851968446365696.
I have a bunch of objects that i instantiate and i have a follow script on them and they follow me, but how do i set their rotation to face me?
transform.LookAt(playerPosition)```
Visual Studio on Mac is practically featureless xD
thanks, although this did work because the mesh was facing the opposite direction of what it was supposed to look at so i further had to rotate it by 180 degrees on y axis
Better fix is to fix your mesh 😉
But there is limit of area masks which is shared across all agents. I'm looking something which is not shared by all agents.
Alright so this was the original question.
Sounds like you want the object to have a script that has a list of gameobjects or renderers, and you would add/remove objects in that list when they enter/exit your trigger.
When the player enters, you can loop over the list and unhide the objects, and clear the list
Was this the script written by ChatGPT?
If you want to disable all objects on the floor, you could put them under an empty parent and just disable the parent gameobject (instead of collecting them into a List like I suggested above)
rotating/shifting/scaling a mesh is a 60 second operation in blender 👍
yes it was lol 🤣 I wrote my own script for hiding/toggling roofs and floors when the player collides but this was a starting point for hiding players and monsters (and other objects) on other floors because it seemed like a really complex task
that works for objects that are there all the time (like furniture in a static building) but it doesn't work for gameobjects that come and go (like mobs, enemies, other players). I haven't found anyone working on a similar problem online
Okay then I suggest collecting them into a List in TriggerEnter/Exit
oh that's a good idea!! thank you
if i want to do onCollisionEnter do any of the two GO need to have rigidbody ?
, after horizontal
nope I don't think so
yes, please read the Unity documentation
Horizontal with capital H
Are there any examples I can follow yet of inline raytracing in unity? from what ive seen the documentation on it is very very sparse
hello, does anyone know how can I get informed when recenter event occurs (right Oculus menu button long press) with XR Plugin Management?
target is to implement recenter in my app on right Oculus menu button long press...
does anyone know good examples of enemy ais in sidescroller games?
hey everyone, is there any way to get a sprite into a tilemap with code? i couldnt find any helpful information about it on the internet pls help me out
Hey, I need to sort small lists (usually 1-20 elements, rarely above 30) extremely efficiently. The keys are positive floats. They tend to be near-sorted a lot of the time so the default quicksort used by List.Sort() may be the bottleneck, and I'm looking for a better algorithm for this scenario.
Here is an example of a typical list:
[14.43493, 65.56322, 172.989, 213.8974, 257.5395, 324.424, 346.906, 357.6949, 368.1883, 0.2753617, 0.419436]
As you can see the list is almost sorted, except for the last two elements which are at the wrong end. It is quite common for the list to be made up of some number of ordered subsequences. As such, what is the most efficient sorting algorithm for this? I am thinking of using Insertion Sort but it does not take advantage of the subsequences being sorted. I would prefer one which splits up the list as such and re-orders the subsequences based on their first and last element, and handles overlaps appropriately:
[14.43493, 65.56322, 172.989, 213.8974, 257.5395, 324.424, 346.906, 357.6949, 368.1883], [0.2753617, 0.419436]
Does something like this exist? Would handling overlaps be too big an overhead?
bubble sort
Question! I'm positioning a bunch of walls right next to each other with this line of code:
wall.transform.position = previousWall.transform.position + -1 * previousWall.transform.up;
The issue is that they are getting spawned/positioned directly next to the previous spawned-in wall while the wall is moving. This leads to some inconsistencies on where the walls actually get spaced. How can I ensure that they are always directly next to each other (no space between)?
Note: If the walls are not moving, they spawn in correctly. I think its an issue with the previous wall moving a pixel or two during the calculation of the next one.
the problem may be you are mixing float and int math
Switching -1 to -1f didn't affect anything and there is no other math happening here (other than the vector addition)
well, if that is not the case then the obvious answer is to cache the position
Are they moving with a rigidbody?
You could try rigidbody.position instead of transform.position
Im assuming youre updating previousWall to be the newest wall after creating it?
Yep its a pretty simple movement script:
rigidBody.velocity = new Vector2(0, fallingSpeed.getSpeed() * (1 / parallaxMultiplier));
Yeah I have a list of wall GameObjects that I'm pushing/popping to.
GameObject previousWall = walls[walls.Count - 1];
What do you mean by caching the position here?
it would seem that there is a mismatch between position and actual position. As you are using physics then this would indicate a mismatch between Update and FixedUpdate positions, so you have a choice, move your code to FixedUpdate or cache the FixedUpdate position and use it in Update
What is going on with my compute shader, why are the alpha maps being tiled like that?
I have 8 terrain layers and the compute shader sets the alphamaps for the terrain using a texture2d to find the closest color from the terrain layer diffuse texture, but its not working the way its intended to work.
The 1st image its how im getting the result from the GPU, and the 2nd image is how im getting the results from loops in C#.
Switching to FixedPosition got it closer, but there are still spaces about 10% of the time.
hi guys I'm stuck on a current issue with coding a shotgun that uses raycasting to give it an accurate and randomized spread; it can randomize it's point however I'm using a trail renderer to imitate that it's actually shooting a projectile. I'm trying to figure out how to still draw a trail even if the raycast is unsuccessful; by trying to use the direction of the ray but it's not working - if anyone has a realistic method of going about implementing this, it'd be heavily appreciated. the current code is:
private void ShotgunFire()
{
for (var i = 0; i < shotgunPelletCount; i++)
{
var accuracy = Random.insideUnitCircle * shotgunSpreadSize;
var dir = new Vector3(accuracy.x, accuracy.y, 1f);
var sprayDir = transform.TransformVector(dir);
Debug.ClearDeveloperConsole();
Debug.Log(accuracy);
var ray = _playerCamera.ScreenPointToRay(Mouse.current.position.ReadValue() + accuracy);
var targetPoint = Physics.Raycast(ray, out var hit) ? hit.point : -sprayDir * 30f;
TrailRenderer trail = Instantiate(bulletTrail, shotgunSpawnPos.transform.position, Quaternion.identity);
StartCoroutine(SpawnTrailAlternative(trail, targetPoint));
switch (hit.transform.tag)
{
case "Enemy":
var collidedEnemy = hit.transform.gameObject;
collidedEnemy.GetComponent<EnemyController>().TakeDamage(shotgunDamage);
break;
case null:
break;
}
}
CurrentAmmo--;
if (CurrentAmmo > 0) return;
_playerInventory.ExpireWeapon(_playerInventory.CurrentCard);
}
I've also tried it with this
var targetPoint = Physics.Raycast(ray, out var hit) ? hit.point : ray.direction * 20f;
however it doesn't shoot straight ahead and instead either to the side or behind the player
How can I change the editor camera's position from a script?
Yeah, but the currentDrawingSceneView is always null
Not what you want then
How about this one? https://docs.unity3d.com/ScriptReference/SceneView-lastActiveSceneView.html
I assume currentDrawing is only set during a scene view repaint or whatever
I am trying to change the pivot point of a hud element to the location of a mouse input, but im struggling on converting the pivot point to world space. How can this be done?
It depends on which canvas render mode you're using
oh damnnnnn
That one Isn't null but changing the camera position doesnt do anything. Hopw do I know I've got the right one?
that was probably the most useful thing someone has ever said to me ever, that would have changed everything sixteen centuries ago
thank you
Yw lol
UnityEngine.AI.NavMeshAgent:SetDestination (UnityEngine.Vector3)```
how do i fix this
i've got a baked navmesh on my floor
and a navmeshagent
hello 🙂 My objects have no shadows as you can see in the image, any tips? thanks!
This is not a code question. See #🔀┃art-asset-workflow instead
okk, thanks
When should I be using a Singleton Pattern?
I have a player script and there will only ever be one player
wondering if its worth making it into a singleton
is there a quick way to get a scene’s build index using the scene’s name?
Use GetSceneByName and access the buildIndex, that should work
Why do you need this though?
Yeah used this, thanks. GetScneByName only works if scene is already loaded
specific stuffs really
Buffer.BlockCopy(webRequestBuffer, 0, webRequestBytes, 0, 1024);
Decoder myDecoder = Encoding.UTF8.GetDecoder();
// Full string no problem
Debug.Log(new string(webRequestBuffer));
myDecoder.Convert(webRequestBytes, 0, 1024, webRequestBuffer, 0, 1024, true, out int one, out int two, out bool three);
// Only first letter, despite char buffer being full
Debug.Log(new string(webRequestBuffer, 0, 1024));```
After the decoder convert, the char array is having trouble getting processed back into a string
When I create a new string with that char buffer after the convert, it only copies over the first character to the string, no matter what I do
before the conversion, the entire char buffer goes into a string just fine
The char buffer is also full of characters after the conversion. I can see if I loop through them
Help
Saying "Help" with absolutely no content to what problem you're having is difficult to answer.
I have a [SerializeField] Camera worldCam; but when I try to add the camera it doesnt let me
That's a beginner question pal
my bad
Sounds like the object your dragging does not have any camera component attached.
drag the component in, rather than the gameobject. If that doesn't work, just grab it through C#
Camera myCamera = GameObject.Find("someObjectWithCamera").GetComponent<Camera>();
Camera.main 😄
Then you're doing something wrong
thats what Idk what Im doing wrong
Which object is your camera component on
oh nevermind
Just drag the main camera on to your variable
If that doesn't work then you need to screenshot the inspector view of the variable
I'm not much help. I don't drag stuff in, I usually just initialize through C#
Sorry
I think to drag stuff in, it has to be in the same hierarchy
Like you can't drag a camera from your scene inspector hiearchy, into your asset in your asset folder
hmm
But that's weird because your game controller is in the same hierarchy view
yeh
Make a new camera in your scene inspector view
right click -> new camera
try with that
restart unity?
Just out of curiosity, change [SerializeField] Camera worldCam; to public Camera worldCam;
no clue then
dang
You will have much better luck in the beginner section
k
Share the game controller script
k
@elder jay Click on this and see what pop up on the list -
The Camera I was trying to add
still didnt work that way
It's probably not the case here, but an OnValidate that immediately nulls the reference could do something like that.
Something seems very wrong with this....
Though from the video, it looks like it's not letting you drop it in. It's got the crossed circle when you hover over the reference field
In this case they might have a class called Camera in the project.
using System.Collections.Generic;
using UnityEngine;
public enum GameState
{
FreeRoam, Battle
}
public class GameController : MonoBehaviour
{
[SerializeField] PlayerController playerController;
[SerializeField] BattleSystem battleSystem;
[SerializeField] Camera worldCamera;
//public Camera worldCamera;
GameState state;
// Update is called once per frame
private void Start()
{
playerController.OnEncountered += StartBattle;
battleSystem.OnBattleOver += EndBattle;
}
void StartBattle()
{
state = GameState.Battle;
battleSystem.gameObject.SetActive(true);
//worldCam.gameObject.SetActive(false);
var playerParty = playerController.GetComponent<PokemonParty>();
var wildPokemon = FindObjectOfType<MapArea>().GetComponent<MapArea>().GetRandomWildPokemon();
battleSystem.StartBattle(playerParty, wildPokemon);
}
void EndBattle(bool won)
{
state = GameState.FreeRoam;
battleSystem.gameObject.SetActive(false);
//worldCam.gameObject.SetActive(true);
}
private void Update()
{
if (state == GameState.FreeRoam)
{
playerController.HandleUpdate();
} else if (state == GameState.Battle)
{
battleSystem.HandleUpdate();
}
}
}
So it thinks the object you're dragging in DOESN'T match the reference field's type
Try this, see for sanity checks?
[SerializeField]
private Camera _cam;
public Camera Cam
{
get => _cam;
set {
_cam = value; // add a breakpoint here, see the stack trace?
}
}
Change all of your camera reference to use "Cam" instead.
k
It kinda looks like their pointer is offseted too..?
Perhaps the field doesn't get the drop down event.
still did the same thing
Here's another (unlikely) possibility: Do you have a script called Camera that you made yourself?
Read the comments...
Actually I might
Refrain naming your class with an already existing class name, how is it that you haven't receive any compiler errors?
If you ever need to make your own scripts that have the same name as UnityEngine stuff, put it into a namespace to avoid ambiguity
No clue
Something awfully suspicious here, if that was the case.
I completely forgot about that Camera script
Ah yes... the namespace...
Ah ha, unlikely possibility FTW
I have a game planing going on in which player squats with the mobile by keeping the mobile in landscape left format, is it possible to identify whether player is squatting accurately with his mobile, currently we have an idea of checking mobiles accelerometer values but its not accurate ,
You want other players to check if a player is squatting?
No i want the player holding the device to be checked, like example detecting how many squats have the player achieved while holding the mobile in front of him
Oh, for some reason I read the word "multiplayer" in your text
can you use shader graph if you dont use URP ?
You'd probably have to check the mobile accelerometer for that regardless even if it's not accurate, maybe the gyroscope (if that would even help considering that sensor is specifically rotation-oriented). Problem might be the device itself. Some manufacturers cheap out on the sensors inside their devices, leading to accuracy issues from poor-quality components.
Yeah i have heard that too the values differ in devices, anyway will check with accelerometer and gyro thanks guys
I'd imagine the gyroscope being in-tandem with the accelerometer, being used to account for any device rotation that happened when the user was squatting with the phone in their hand / on their person(s). It probably won't help on it's own though.
can you use shader graph with normal renderer pipeline(I am not using URP or HDRP) ?
AFAIK, no, it's URP and HDRP only
I want to override sprite geometry every frame with a varying number of vertices/triangles. Is there any way to do this without allocating a new array each time?
I can't see a way to set the vertices with an array that exceeds the length of the sprite.
https://docs.unity3d.com/ScriptReference/Sprite.OverrideGeometry.html
So if I have 5 vertices, then 10 vertices, then 4 vertices, I will need to create a new array each time.
How can I do this without throwing arrays in the garbage each time?
you can use array pool from https://learn.microsoft.com/en-us/dotnet/api/system.buffers.arraypool-1?view=netstandard-2.1 or from visualscripting
i mean you know how to do this, i assume you meant if this already existed
i think this is what this arraypool class is for
Could use ShaderForge 😄 @whole night
Yes you can, since 2021 I believe, shader graph is supported in BRP
Right, so pooling an array of every length.
Guess that's an option.
Pretty annoying they don't let you pass a length in with the arrays.
Retrieves a buffer that is at least the requested length.
wont' work, but I could make my own
Looking for a person to create a mobile game. write in private messages
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
Why do all Mesh.SetTriangles overrides take a submesh? If I use 0 for the submesh will that apply to the single mesh?
For SetVertices we have:
public void SetVertices(Vector3[] inVertices, int start, int length, Rendering.MeshUpdateFlags flags = MeshUpdateFlags.Default);
Because Unity's meshes are made of of a single vertex array and any number of submeshes (indices into that data)
If you only have one submesh in the first place, then yes, 0 is the single mesh
Hi, i want to make a plane with the shape of my Field of View
using UnityEngine;
public class ViewportQuad : MonoBehaviour
{
public Camera camera;
private float distanceToCamera;
private MeshRenderer meshRenderer;
private void Awake()
{
meshRenderer = GetComponent<MeshRenderer>();
distanceToCamera = 0.5f / Mathf.Tan(0.5f * camera.fieldOfView * Mathf.Deg2Rad);
UpdateQuadSize();
}
private void Update()
{
UpdateQuadSize();
}
private void UpdateQuadSize()
{
if (camera == null || meshRenderer == null) return;
float aspectRatio = camera.aspect;
float screenWidth = Screen.width;
float screenHeight = Screen.height;
float quadHeight = 2f * distanceToCamera * Mathf.Tan(0.5f * camera.fieldOfView * Mathf.Deg2Rad);
float quadWidth = quadHeight * aspectRatio;
meshRenderer.transform.localScale = new Vector3(quadWidth / screenWidth, quadHeight / screenHeight, 1f);
}
}
can someone tell me what i have to change to achieve that? i dont see my mistake
the scene looks like this
I don't understand why you're dividing by screen width and height, or why you're calculating the distance if your quad was 1 high?
Where do you actually want this quad in space?
If it's where it is already, then surely you want to be using the distance it is to the camera at some point? And not just calculating something else entirely
Is there a way to get current scene load handle? Particulary for first scene load
my actual goal is to create a plane to resterize the scene at that region and then compare the values with the values in the Field of View.
i tought i create a plane and position it at the field of view and with the script it should scale to the field of view
So does this not work?
float distanceToCamera = Vector3.Distance(transform.position, camera.transform.position);
float quadHeight = 2f * distanceToCamera * Mathf.Tan(0.5f * camera.fieldOfView * Mathf.Deg2Rad);
float quadWidth = quadHeight * aspectRatio;
transform.localScale = new Vector3(quadWidth, quadHeight, 1f);
Thanks. :-)
There can be more than one "current" scene, but one will be considered "active". You can get it here:
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.GetActiveScene.html
You'll only have multiple scenes if you load additive
Runtime!
You can also get the scene from any GameObject
https://docs.unity3d.com/ScriptReference/GameObject-scene.html
All the SceneManager stuff is runtime. There's an editor version too if you need it
But that's quite a different use case.
🤔
?
that's very interesting
isn't it what you wanted?
oh wait... "scene load handle"
I don't know what that is
This is to get a handle to the scene itself
when you load scene you get operation handle
which provides you data about current loading operation
Ah, well there cannot be a load handle to the current scene because the current scene would already be loaded
great thank you
I believe the first scene loads before any code runs, but what you can do is have a very lean scene that is your loading scene
And put a single script in that that loads your scene in the background
I have our company logo/splash in a scene like this
that's not true
you can run code at any point of time
even before all dlls are loaded
Hm. Okay, well I'm not sure how to do that
through attributes on static methods
Like RuntimeInitializeOnLoad?
yeah
yeah
Well...
You can't do that until you have a rendered frame
And you can't have that before the first scene is loaded
So I'm not really sure what RuntimeInitializeOnLoad has to do with it
I'm pretty sure it wasn't here before
No, it's been around for many years, I can't remember when it was added.
It was available in 2017
So it's at least 6 years old
Looks like it was introduced in 5.3
So 2015
😮
I do basically all my scene management via additive scenes
yeah, this should be indeed very interesting
but I'm so sceptical about it, so I literally making a build rn to check it works runtime xD
Can't believe it until I see it with my own eyes 😅
@unreal temple sir, what about runtime scene saving? Are you familiar with that sort of stuff?
That's not how I do save games.
it's not for game saving, it's for runtime level editor thingy
The way we have done a runtime editor is treat like a save game. Serialize the changes to the scene in our own data format and then recreate it at runtime
sure, that's the thing, but I'm curious for scene format
cause if that's a thing, I don't have to write my own format
Im pretty sure that the yaml scenes are stored in gets crunched into some unity black box format when build
how to i get the rotation of transform as if it used lookat? i want to smooth it))
OOOO
public void DisplayMessage(string text, Sender sender)
{
Image messageBox = Instantiate(_messageBox, _scrollRect.content);
TextMeshProUGUI messageText = Instantiate(_messageText, _scrollRect.content);
messageText.gameObject.SetActive(true);
messageBox.gameObject.SetActive(true);
messageText.text = text;
messageText.ForceMeshUpdate();
Bounds bounds = messageText.bounds;
messageBox.rectTransform.sizeDelta = bounds.size;
}
messageText.bounds.size is very inaccurate and also very big, i am not sure what's causing this, does anyone know why?
i have a worldscene and i have built an interactive map.
when i press M i want to switch between both views.
Whats a proper way to handle that?
have world and map in two gameobjects, only one enabled at a time?
disable worldcamera, enable map camera?
Hello all, I would like to ask you.
I am working on my asset (which possibly could be published to asset store). How I can ensure in my code - that even the end-user change the folder based on his requirements (for example to Assets/3rdParty" folder) How I can check / setup my code that it always will have an access to correct "asset folder" ?
Hey hey guys, I've a doubt about which would be the best approach for a zoomable and scrollable 2D grid map.
Explaining a bit of the idea, it would be having an image that would be the background of the map, and the game would develop there. I would have a grid to create events on certain points of the grid, create NPC movements etc.
I have in a certain way a structure for the gridcell already defined (I can provide it, but i don't think it's necessary for what i'm looking for) and some base code.
Here are the following problems i've found so far (And idk how to handle):
If i use an GameObject to hold the image and then use the camera to zoom in and out, it may present some errors when it comes to the Aspect ratios and maybe it could potentially zoom out a lot? (The zoom can be fixed by having an underlay with the same background color as the map.
If i use an image in a canvas, the image can be zoomed (scaled) but the grid won't do the same thing. (Can this be the best way to approach it but handle the zoom + X/Y position of the click?)
Has anyone ever done a grid system in a 2D world that can be zoomed in or zoomed out that could kinda point me in the right direction?
I would define a JSON format for your maps and then load to and from that
well yeah, it seems like that's the only choice so far
quite weird they implemented runtime scene creation
but no runtime serialization of it
I wonder if any of you guys would be able to help me set up an IK rig for a character from Mixamo with the animation package? I'm pulling my hair out a bit over this!
Guys I have wierd results with camera.WorldToScreenPoint.
worldPos = new Vector3(7.58f, 0f, 4f);
camera.WorldToScreenPoint(worldPos) returns (4699201.00, -2872043.00, 0.00)
What am I doing wrong? My camera setup:
Why are the values so big
Hi guys! What is the best way today of culling UI elements. I want to disable UI element gameobject when it outside of scroll view.
I am looking for the quickest way to optimize drawing sprites without the overhead of thousands of game objects.
Simplifying the images to tiles and drawing tiles worked fairly good, but I don't get to place them in-between the tiles.
I think going straight to applying pixels to a texture may be even better.
So I tried SetPixels(), on to a separate texture, and only apply it to the screen when it gets through all of the characters. (lets call them goblins) Eventually this will be multi-threaded, but for now I am just limiting the amount of time it has, to keep a reasonable frame rate. It picks up where it left off the previous frame)
Anyway, 100,000 of my little 8x8 pixel image takes about 12 frames to be drawn when formatted as a R8, and also unchanged as RGBA 32 bit. I would expect a performance increase with the shorter bit format.
Does anyone have advice for the fastest method to do this? I would love to be able to push this up to 1,000,000 characters processed, even if I have to slash down the image quality.
Thanks
Are you using DOTS?
nope
I just have a separate C# class to handle it. All I want is a unit type (enum) and an int for the mapLocation.
@lost delta I think when case is 1kk of something rendered then you should look at GPU instancing
hmm... I think this is more or less what I'm building, just in a single class. I have one single tiny sprite texture, that I use to apply multiple copies of the same thing based on an already established array of data.
Is the difference here that it is the GPU rather than the CPU doing the calculations?
I am sticking to 2d if that makes a difference
@lost delta no difference in result, but I would expect difference in performance. Instancing happens all on GPU side, so CPU not loaded so much. In your case you doing tones of work (1kk coping something to same texture) on CPU and then just 1 simple drawcall on GPU
hmm... are Tilemaps GPU instanced?
@lost delta guess it's not, because you can use regular material with GPU instanced checkbox disabled. I think tilemaps do some performance tricks though
lol very small spaced tiles. about one pixel across😅
I think that the problem is always not in how many pixels you have but in how many actions your CPU does to render it
This is one of the best use cases for DOTS, so why don't you use it? 1.000.000 should be easily doable in DOTS.
There are a bunch of examples, some in older versions of people that have animated sprites in DOTS already.
I mostly haven't used it because I am unfamiliar with it. But my 8 byte array ends up being 8 megabytes when I have 1,000,000 instances, and it is hard for me to imagine using a game object would be more efficient. I suppose the efficiency here is drawing them, not holding their information in ram.
It's not about holding something. It is about all times you rewriting data to texture. If it happens ones or really rarely then ok, that is your case. But if your 1kk goblins will run and jump across the screen, then you will ended up with writing to texture 1kk times.
https://github.com/fabriziospadaro/SpriteSheetRenderer
This was the one I used ~a year ago, the problem that this one only did 1 million, was because the sprites overlapped, which caused z-fighting, which dropped the FPS significantly. When spaced out I got way more. With the new versions of entities, you get way better performance then 0.17, so I wonder how many millions of sprites you could get if you updated this. Anyhow, I think this is a way better approach, at least for the sprite rendering part. You can also go hybrid if you want.
Also I've implemented similar up to date solution but without any limiting of how to use it for animation / sorting and stuff. https://github.com/Antoshidza/NSprites
Thank you both so much! I will look into this
Am I mistaken or do I see a NativeCounter that can be incremented from a parallel for job? Just today I got the need to implement this.
Looks cool, gonna check it out this weekend. 
It is possible to save the child (Camera) before destroying its parent?
yep. Also in separate assembly, or just copy the code 🙂
Transform.DetachChildren() https://docs.unity3d.com/ScriptReference/Transform.DetachChildren.html
Thank you
Description
Unparents all children.
Useful if you want to destroy the root of a hierarchy without destroying the children.
See Also: Transform.parent to detach/change the parent of a single transform.
I tried DetachChildren too, but it didn't work
Try setting the parent to null?
{
Instantiate(PlayerListItemPrefab, playerListContent).GetComponent<PlayerListItem>().SetUp(player);
}``` gives an error like: ```The type or namespace name 'Player' could not be found (are you missing a using directive or an assembly reference?)``` why isn't it working?
Do you have a class called Player?
import the namespace?
yes
post the script
maybe you have the old version of photon
im not sure really lol
try to import the package again or whatever
ok i will try
you're on the start of a very long journey
what are you trying to do?
and do you have a screenshot of your game?
remind me to make this quote into a nice desktop background and send it to you! one of your favourites, haha
lol
what are you trying to do?
like what's the game?
destructible terrain?
something like this, but bigger and smoother with more variety of characters:
https://www.youtube.com/watch?v=c3FFuJy61nM
Doing a performance test for using tiles and arrays instead of game objects for Unity
Not sure how I cropped it poorly
like.. tilt your phone and thousands of little guys roll over to that side of the map
check dms - expecting to see this littered around the code channels soon 😄
Hi! I'm currently experiencing a bug where the rope on my character's fishing rod seems to "lag behind" a frame or so. The rope is made out of a LineRenderer, as well as some kind of gravity simulation for the rope as well as the hook.
I've tried putting the DrawFunction in LateUpdate, FixedUpdate, Update, and OnPreRender. Regardless of the method used this resulted in the same bug, with OnPreRender being the exception where the rope didn't render at all. The rope is also on an overlay camera that only renders weapons. Unchecking "Use world space" temporarily fixes one of the rope segments, but breaks the other.
This code wasn't written by me, so I'm not exactly sure where to start looking to debug something like this. I'd appreciate any help available with this. Thanks!
lol
so is your approach right now to use unity tile maps?
there's a lot of nuance as to why this error is occuring
I understand that, trying to give as much information as possible so I at least know where to start looking.
right now what is happening is
- start of frame
- the position of the line renderer is calculated with respect to the position of the fishing rod. at this point in time, the fishing rod's position is still the same as it was in the previous frame.
- the player's input is read and the movement is applied to the camera
- the fishing rod is repositioned with respect to the camera. at this point, the line renderer appears to be in the wrong place.
- render the frame
or
- start of frame
- the player's input is read and the movement is applied to the camera
- the position of the line renderer is calculated with respect to the position of the fishing rod. at this point in time, the fishing rod's position is still the same as it was in the previous frame.
- the fishing rod is repositioned with respect to the camera. at this point, the line renderer appears to be in the wrong place.
- render the frame
yeah, that is currently shown in the video. it works surprisingly well, but I am only have one type of unit, and am grouping them up to groups of 8 on a tile
yeah you were saying something about 1 million... you mean when you zoom out? is that what you're working on right now?
so we'd want to calculate the line-render after repositioning the fishing rod, right? Isn't that what lateUpdate is for?
Is it possible to track Flick speed/inertia using a mac trackpad in Unity?
you probably stuck the code that moves the camera with respect to the player input into lateupdate
similar to how ive seen it in mobile touchscreen games
clearly the order of the LateUpdates are not in the order you want*
Yeah, I have a fairly optimized method of keeping track and updating the cute little guys, i'm just exploring the best way to render them. Looking into DOTS next.
Camera movement is just in regular update, so that's not it.
well the snippet i described is what's happening
i can't see your code, so i don't know which callbacks you are putting this stuff into
it sort of doesn't matter
the positioning of the rope is strongly coupled to the fishing rod's position
here it is regardless, but alright. just strange how this issue only affects the rope and nothing else in the scene.
https://pastebin.com/wQTHLy2x
i don't think it's strange, exactly what i am describing is what's happening
this can be easily resolved by moving the code that positions the fishing line points to be after the fishing rod is positioned with respect to the camera
LineRenderer itself may use LateUpdate to update the mesh with respect to the points. so if you are doing this all in a LateUpdate, you may have to call a method on the line renderer to update the mesh manually after you have changed its positions
well this is buggy
and the latter applies even if the fishing rod is just a child to the player object.
you have to make an attempt at comprehending what i am saying
none of that matters
the rope is simply strongly coupled to the position of the fishing rod. you have to do that work in the same place
it cannot be decoupled like it is now
this is using fixed update to move around the points. the camera will be "later" than a fixed update
the reason the gap is big is because the camera is positioned on update, where the input is read
but fixed update is run before update, so the input is from the previous frame
i.e., the apparent camera position read by the fishing rope is the previous frame's camera position, and hence the previous frame's fishing pole position
look at my snippet. that is what's happening
alright, sorry for asking irrelevant questions. I greatly appreciate the help, really. thanks for explaining this so thoroughly. I'll take a crack at it and come back if I have any more questions.
hmm
am i making sense?
you have to find the code where the camera is positioned with respect to player input.
After that occurs, you have to calculate at least the first few positions of the fishing line with respect to the fishing pole. it sounds like the pole is a child of the camera transform, so its position will have been updated at that point
then you have to apply the positions
then your bug is solved
sweet, thanks again. just need to go through it all step by step now and i'm sure i'll figure it out!
lol
i'm sure [you]'ll figure it out!
i'm supposed to say this part when someone is really confused, not the confused person
pfft well fair enough. the step by step breakdown helped a ton in understanding it all though, so thanks again!!
I've got a code that rotates the enemy's gun towards the player so that the enemy can shoot the player. But, the attackPoint (which is at the barrel of the gun) doesn't shoot straight but sideways. and when the gun rotates towards the player the barrel doesnt face the player, instead the side of the gun faces the player.
Transform attackPoint = enemyGun.transform.Find("attackPoint");
if (Physics.Raycast(attackPoint.position, direction, out hit, Mathf.Infinity))
{
// Rotate the gun towards the hit point
Quaternion targetRotation = Quaternion.LookRotation(hit.point - attackPoint.position);
enemyGun.transform.rotation = Quaternion.RotateTowards(enemyGun.transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
if (!alreadyAttacked)
{
// Attack code here
Rigidbody rb = Instantiate(projectile, attackPoint.position, Quaternion.identity).GetComponent<Rigidbody>();
rb.transform.forward = attackPoint.forward;
rb.AddForce(enemyGun.transform.forward * shootForce, ForceMode.Impulse);
rb.AddForce(transform.up * upwardForce, ForceMode.Impulse);
// End of attack code```
idk how to fix this
Have you made sure your gun model is actually imported properly, facing forward?
probably not, what do you mean?
the "forward" of your gun model might not match with the visual forward
with tool handle rotation set to local, if you select the gun object, the blue arrow should align with the barrel of the gun
how do i make it match then?
I just got the blend file and dragged it into my models
ok let me check
if it doesn't, you need to fix the model export from blender
Now you know your issue
thanks a lot
I have a audio clip whose volume i want to reduce, how do i do that?
doing audioSource.volume = 0.3 does not reduce the volume
Through the audio source is how you lower the volume, as the audio source plays clips - you might be affecting the wrong audio source, or something may be overriding the volume level, or you might have a mixer on the source affecting the volume
how can I make a TMPro TextMeshPro appear above its parent, which uses a normal sprite?
IIRC, the top-most elements in a UI's hierarchy are drawn first (so they appear behind other elements) and the lowest elements are drawn last (so they appear above everything), if you want your text infront of an image, assuming the text is not nested in the image, the text should be lower in the Canvas hierarchy than the image
nothing happens when i press download button (not downloading)
ah, thats the issue, the object needs to be a child
any tips?
I'm trying to create an enemy spawner that creates a new instance of an enemy at a fixed rate. However, whenever I try to create a new enemy, the first one gets destroyed. Is there some functionality of Instatiate that I'm missing here?
public class DroneSpawner : MonoBehaviour
{
public GameObject enemies;
public GameObject drone;
float coolDown = 1.3f;
// Start is called before the first frame update
public void Start()
{
Invoke("SpawnDrone", 2);
}
void SpawnDrone()
{
GameObject newDrone = (GameObject)Instantiate(drone, enemies.transform);
newDrone.transform.position = gameObject.transform.position;
Invoke("SpawnDrone", coolDown);
}
}
is drone a scene object or a prefab?
and you’re directly dragging the prefab from the asset folder into the drone field?
Where is your code that destroys enemies?
Also your (GameObject) cast is unecessary
Yes
I don't have any, that's the issue
The easiest solution might be to use a empty RectTransform as the parent, then you can sort the image and texts both as children - though if "InventBG" is the white square, it looks like another UI element or canvas is infront of it, unless your text color is meant to be grey
objects don't just get destroyed willy nilly
you must have some. What scripts does the prefab have?
`public class Drone : Enemy
{
int score = 100;
enum DroneState
{
searching,
mining,
collecting
}
DroneState droneState;
// Start is called before the first frame update
protected override void Start()
{
base.Start();
droneState = DroneState.searching;
}
// Update is called once per frame
protected override void FixedUpdate()
{
base.FixedUpdate();
}
public override void HasHit()
{
Remove();
}
public override void Remove()
{
GameManager.Instance.playerScore += score;
CollManager.Instance.scope.Remove(gameObject);
Destroy(gameObject);
}
}
`
Remove is the only way to destroy it, and it's not being called
also !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.
how do you know it's not being called?
Put Debug.Log in it
ColManager.Instance.scope is the list of all game objects that I'm using for collisions and stuff. Any time a game entity is destroyed, it should remove its reference from scope. That's what Remove is for. However, the issue I'm having is that Scope is being cluttered with null references, which should be impossible and is causing bugs.
if Remove was being called, the reference would have been removed from scope.
sorry
- Fix your null reference exceptions first
- Add Debug.Log to Remove to make sure it's not being called
The NullReference exeptions are a result of the GameObject being destroyed, which is what I'm trying to fix
GameObjects being destroyed will not cause a NullReferenceException
they will cause MissingReferenceException
If you have NullReferenceException it has nothing to do with objects being destroyed
Then I guess I meant MissingReferenceExeption
ok and on what filename/line number is this happening?
show the full stack trace
(the preview section at the bottom of the console window)
Is there a way to know if the Animator's Controller is a controller itself, or an override of one? I'm trying to write a script for managing custom animations for stuff like weapons and scripted sequences by just having a few "generic" animations that I intend to dynamically swap during the game, with overrides, and RN it seems that on a startup it gets the initial animator from my character, and not the actual override controller I've assigned to it. So I want to include an "if" statement that checks whether it's an override or not there.
public void Start()
{
animator = GetComponent<Animator>();
RuntimeAnimatorController anim = animator.runtimeAnimatorController;
animatorOverrideController = new AnimatorOverrideController(anim);
animator.runtimeAnimatorController = animatorOverrideController;
clipOverrides = new AnimationClipOverrides(animatorOverrideController.overridesCount);
animatorOverrideController.GetOverrides(clipOverrides);
}
that totally fixed it. no idea why anyone would think drawing the rope before simulating it is how it'd work. LateUpdate in the right order fixed the issue.
thank you for your thorough help!
I know where the error itself is happening and how to prevent it from crashing, but knowing where the missing reference is being called doesn't help me find why the GameObject is being destroyed in the first place.
show us
maybe we can help
but without details, hard to help
cs
public static bool HasCollision(GameObject a, GameObject b)
{
//Missing Reference Preventers
//if(a == null)
//{
// Debug.Log("GameObject a was null");
// return false;
//}
//if (b == null)
//{
// Debug.Log("GameObject b was null");
// return false;
//}
if (a == b) { return false; }
CollisionBox aBox = a.GetComponent<CollisionBox>();
CollisionBox bBox = b.GetComponent<CollisionBox>();
float distance = (b.transform.position.x - a.transform.position.x)* (b.transform.position.x - a.transform.position.x) +(b.transform.position.y - a.transform.position.y)* (b.transform.position.y - a.transform.position.y);
if(distance < Mathf.Pow((aBox.radius + bBox.radius), 2) )
{
return true;
}
return false;
}
This is the code where the MissingReference is being thrown, in the collision checker.
Which makes sense, the collision checker loops through all objects in the scope and uses this to check if the two objects have a collision. The issue isn't that this method fails if there is a missing reference, the issue is that there should never be a missing reference
I was pretty sure that the issue must have been from some kink of the Instantiate method that I wasn't aware about, but if that's not it then I have absolutely no clue what could be causing this.
Are you reloading any scenes?
Otherwise, search your code for Destroy calls
The only other destroy that's not inside of a Remove method is in my singleton implementation
cs
public void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(this);
}
else
{
Instance = this;
}
}
(This is in GameManager)
Are you sure it doesn't have something to do with using the same reference to refer to the new GameObject instance?
newDrone = Instantiate(drone, enemies.transform);
newDrone.transform.position = gameObject.transform.position + new Vector3(0,0,5);
Where newDrone is named in the class
Don't leave space before cs
It doesn't matter, no, though I don't see why you would need to make that a class variable
where the hell is "gizmos"
top-rightmost button in scene window
thank you
@candid kiln And please use #💻┃unity-talk next time for general questions
aight
Maybe one of your Remove calls is forgetting to remove itself from your singleton
Remove isn't being called at all, I checked with Debug.Log
But you have multiple Remove implementations right?
On different enemies?
Drones are just one
This is the first enemy I've implemented
Here's a question
you're doing CollManager.Instance.scope.Remove(gameObject); in Remove
but where are you adding things to the scope?
I don't see that anywhere
In Start()
public abstract class GameEntity : MonoBehaviour
{
[Header("GameEntity Vars")]
public Vector3 direction = new Vector3(0, 0, 0);
public Vector3 velocity;
public float speed;
// Start is called before the first frame update
protected virtual void Start()
{
//Make sure that any GameEntity has a CollisionBox
gameObject.GetComponent<CollisionBox>();
//Add to Scope
CollManager.Instance.scope.Add(gameObject);
}
// Update is called once per frame
protected virtual void FixedUpdate()
{
transform.position += velocity;
speed = velocity.magnitude;
}
public virtual void Remove()
{
CollManager.Instance.scope.Remove(gameObject);
Destroy(gameObject);
}
}
GameEntity is the parent class for anything that is in Scope
So did you add the Debug.Log to GameEntity.Remove or Drone.Remove?
Also shouldn't you just do:
public override void Remove()
{
base.Remove();
GameManager.Instance.playerScore += score;
}```
And can you show the code for CollManager?
Ideally in a pastebin site
That's what I have, I changed it when I was debugging to see if it was the issue but it was not
what is that?
!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.
any of those links
https://gdl.space/ayutahobuq.cs
Like this?
public Button BackgroundButton => _backgroundButton ??=
_rootVisualElement.Q<Button>("backgroundButton");
private void Start()
{
_rootVisualElement = GetComponent<UIDocument>().rootVisualElement;
_backgroundButton.clicked += () => buttonClicked();
SpawnIn(40, GameManager.instance.playerInventory.WeaponList[0], 100);
}```
error says _backgroundButton is not set to an instance...yet it should be...not sure if the _backgroundButton declaration is set correctly
does this code not actually set the private variable?
public Button BackgroundButton => _backgroundButton ??=
_rootVisualElement.Q<Button>("backgroundButton");
Where are you calling GetCollisionsByComponent from?
Can you show that code?
#region collisions
if(CollManager.GetCollisionsByComponent<Astroid>(gameObject, out GameObject asteroid))
{
velocity = -velocity;
}
#endregion
And asteroids never get destroyed?
They do, but they get Removed correctly
So There ARE other GameEntities
Yes
Can you show the asteroid code
Not Enemies specifically though
I didn't know there was a difference 😉
Yeah, I realize that in hindsight haha
Astroids are created in WorldBuilder
(Destructible is the type of GameEntity's that can be hit by player's bullets)
(This includes both Asteroid and Enemy)
I would add some more logs
you need to get to the bottom of this
Inside public static bool HasCollision(GameObject a, GameObject b)
(It's what gives Drone the HasHit method. Which works perfectly right now, btw. If a drone is hit by a laser, it will be Removed, and the next Drone will spawn with no problem)
This seems like it's working fine, though? The only issue is that it's being called with empty GameObjects
Or am I wrong?
I think part of the issue here is that you are letting things have external access to scope
scope should be private, and access to it controlled with public methods
in those public methods you can add more logging etc to see when things are being added and removed from the scope
that can give you some more insight into what's happening
IMPORTANT UPDATE
This works fine:
void SpawnDrone()
{
//newDrone = Instantiate(drone);
//newDrone.transform.position = gameObject.transform.position + new Vector3(0,0,5);
Instantiate(drone);
Invoke("SpawnDrone", coolDown);
}
why don;t you just make newDrone a local variable
That's what I had initially
what does invoke mean
"run this function later"
ou alright thanks
it's a poor man's coroutine
Or a lazy man's coroutine haha
guys so this code is working perfectly fine, but do you think i could have done something better?
btw how do you do this
void SpawnDrone()
{
GameObject newDrone;
newDrone = Instantiate(drone);
newDrone.transform.position = gameObject.transform.position + new Vector3(0,0,5);
//Instantiate(drone);
Invoke("SpawnDrone", coolDown);
}
This is broken again
like how do you do that code thing
Like this
ou sick thanks
will do too now xD
btw nice profile pic
ouuuu nice
I was not expecting to like it but
What's the issue with it? A coroutine if you're wanting this to stop when the GameObject is set inactive: cs IEnumerator SpawnDrone() { var wait = new WaitForSeconds(coolDown); while(true) { Instantiate(drone, transform.position + new Vector3(0,0,5), Quaternion.identity); yield return wait; } }
good show
That's probably a code-beginner question if I had to say
that channel's more active anyways
yeah but like, is there any way i can save destroyed objects when switching scenes
then this way
.
i mean i understand the code and made it somehow without tutorials
but does it really need to be like that
if you post code and not SC more people will probs help fyi
How can I turn on Tonemapping per code?
alr
thanks
for info
Through its volume profile, youd access or cache it with TryGet<T>, a simple example:
public class SomeScript : Mono
{
[SerializeField] Volume fx;
LensDistortion distort;
void Start()
{
fx.profile.TryGet<LensDistortion>(out distort);
distort.enabled = false;
}
}
Thanks
you still haven't reposted the code as a non-sc 😭
Hi, I've got an enemy script and whenever the enemy attacks the player its gun rotates towards the player. I Want the robots hand (the one that is holding the grip/handle) to rotate along with the gun so it looks like the robot is actually holding the gun.
Here's my current code which doesnt work and creates really odd rotations
Quaternion targetRotation = Quaternion.LookRotation(hit.point - attackPoint.position);
enemyGun.transform.rotation = Quaternion.RotateTowards(enemyGun.transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
// Rotate the arm in the opposite direction of the gun
Quaternion armRotation = arm.rotation;
float gunRotationY = enemyGun.transform.eulerAngles.y;
armRotation.eulerAngles = new Vector3(armRotation.eulerAngles.x, gunRotationY, armRotation.eulerAngles.z);
arm.rotation = armRotation;```
here's my desired effect
i made those in the inspector ^
if it was me I would just copy those values from inspector and make it slowly rotate to those values when moving the gun
idk if 3d you use the animator but I do it in the animator for things like that for 2d
oh yeah
how would i make it so that the gun can only rotate 24 degrees max cuz in the pictures the gun is at 24 and -24 degrees i believe
i tried to and it didnt work
if x>24, x=24
then rotate it maybe
alr thanks
y does this not work? its not detecting the collisions.
im trying to check if the player(a cube) is colliding with the maze.
im stuck o how to implement it tho
there's a few different reasons it could be but it probably has to do with what you have in the inspector, the player needs a rigidbody and to not be a trigger or something, the maze needs to be marked trigger, stuff like that
dont' compare tags using string equality, use the CompareTag method instead. also you may want to put a debug.log outside of the if statement to make sure it actually is detecting the trigger
if you find that it is not, then go through this: https://help.vertx.xyz/programming/physics-messages
i already did that
k ill try
could also be you didnt tag the wall with "maze" or stuff like that, maybe try using layers i never go by tag so i dont know what problems can happen with tags
I've got some faulty code, basically the gun rotates to the right and is clamped at 24 degrees like it should be, but bugs out going to a bunch of random numbers and like snapping back and forth.
{
// Rotate the gun towards the hit point
Quaternion targetRotation = Quaternion.LookRotation(hit.point - attackPoint.position);
enemyGun.transform.rotation = Quaternion.RotateTowards(enemyGun.transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
// Limit the y-axis rotation of the gun to the range of -24 to 24 degrees
Vector3 gunRotation = enemyGun.transform.eulerAngles;
gunRotation.y = Mathf.Min(gunRotation.y, 24f);
enemyGun.transform.eulerAngles = gunRotation;
}```
this code is just for an ai rotating a gun towards a player
i did tag it, but how do u use layers for this?
eulerAngles are interpreted from the quaternion at the time you access them. they can also be signed or unsigned. you generally don't want to perform logic on the directly but rather keep your own float that represents the current angle on the axis you want to clamp and add/subtract to that when you want to rotate it, then you clamp the value and assign it as the rotation for that axis
public LayerMask mazeLayer; //Set in inspector, and set all maze objects to maze layer
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.layer == mazeLayer)
{
//Do stuff
}
}
its not detecting, n the code is exactly as the site shows
then move on to the next step. there are many things you need to check and that site walks you through all of them
i might have messed that up honestly its been a while
well for one you shouldn't be comparing a layermask to a layer directly like that
two, if you're going to use layers you might as well go all in with layer based collision rather than comparing the layer ints like that
and three, comparing tags works just fine if you do it right
yeah theres the bitshift stuff, same idea
thats not really relevant but if youre talking about best practices then you want to stay away from strings whenever possible
honestly idk how to make this thing work im just trying to create this effect hold on
this.
using CompareTag is just fine with strings because it takes into account whether the tag is actually spelled correctly and throws relevant errors if it is not
i have no idea how i tried inverse kinematics but it made the robot one not work two all bendy
search "clamp camera" in this discord and once you get past the results of me telling others to search that you'll find plenty of examples of how to clamp a single angle for an object's rotation (which is what you are trying to do)
well what im really trying is to basically have the hand move along w the gun handle. I originally tried IK which failed and then realised that i could maybe clamp the gun to 24 degrees (this degree is the max you can go with both the gun and hand while looking accurate), and then i thought i'd move the hand along with the gun too but thats another thing i'll have to try to do
Can anyone tell me what's null looking at this?
I've tried running debugging but everything seems fine..
Will keep on testing things unless someone has an idea!
Found it I think!
I wish it said which var it is..
If I call a method with [WriteAccessRequired] inside an IJobParallelFor, what happens exactly? Is the method still called concurrently or Unity will schedule and execute the job in a way that it is only acceded once at the same time?
I have an Audio Manager which holds multiple audio clips / audio sources to spawn and despawn whenever the sound is over.
I need a way to change the music in the audio manager whenever I change scenes and so I was wondering if I can somehow set the audio clip to = the audio source of an objecd named Music. So the audio managers SPECIFIC audio clip for playing music would only ever play the audio of the object Music that is in the scene.
Or if there's a code I can use to change the audio for "Music" in the audio manager
Does anyone know how I can do this or any alternative ways?
I havent been able to find the answer anywhere for hours. I feel like I've tried all I know to do it but I dont know enough.
LOL I've been looking through the old messages here to see if anyoen else had the same problem too but I havent found anything yet.
Something on line 196 of Instantiator.cs
im having trouble following that, but how about setting your audio manager to DontDestroyOnLoad and always keep it around
have you attached your IDE to unity's process and hit debug mode? it will throw an exception and stop executing where it's null
(i think, haven't had to do this with exceptions in a while & can't remember if IDE debuggers work the same in unity as it does other processes)
Debuggers don't stop on exceptions by default
But he knows which line it is so easy enough to drop a breakpoint
yup, would be my approach
Thanks for responding
I have it always in the scene. It plays the audio even when I switch scenes which is perfect, but I need to be able to change the audio when I switch scenes.
The problem is that when I switch to, lets say an item shop scene, I want to change the music to a different song, but I dont know how to change my audio managers audio clip without goofing everything 😂
Because since it doesnt destroy on load, the audio stays the same.
If I were to Stop the music, I'd have to make an entirely new audio source in my audio manager which would mean I'd have like 120 different audio sources in my audio manager. But instead, what I had before I had my audio manager was I'd have an object in my scene which contains the music and plays the music attached to itself. But with the audio manager allowing the music to continue between scenes, I dont wanna lose that so I need a way to perhaps... ... Have an object (MusicObject). In that object is the audio and then set the audio clip in a separate object (Audio Manager) to be = to the audio of the first object.(Music Object).
That way the music wont change on load if the Music object in the scene is the same audio clip, but if its a different audio clip then audio manager will play the new one.
I'm not sure how to do that.
If anyone knows audio sources, audio clips or audio managers well, I can share my code. I just really need help 😭
im having trouble visualizing this system with the MusicObject so its hard for me to say, maybe someone will get it
i feel like you can just have all your audio in one place and then assign audiosource.clip whenever you need to, or dont
but again i feel like im just missing what youre trying to do
Maybe I could idk XD
why do you have to make a new audio source?
Because I have walking sounds, jumping sounds, landing sounds, attack sounds, enemy hit sounds, etc...
So the audio manager creates a new audio source and deletes it when the sound is complete
i need to stop answering questions on topics i havent worked on in a long time haha
but is it necessary to delete the audio source when the sound is done?
you could have a separate audiosource for the music maybe
and keep doing whatever youre doing for sounds
It used to do that
Not anymore I got confused
So yeah, like you said, it creates all of the audio sources in the hierarchy as a child of AudioManager
Looks like this in the inspector
I need to find a way to change Clip (under the music at the bottom) when I change scenes to be a specific song for each of my scenes.
why doesnt this work? https://docs.unity3d.com/ScriptReference/AudioSource-clip.html
hmm that example is using a coroutine but i dont think its necessary
if you can access the audio source called "music" here at some point in your scene loading logic you should just be able to change the clip right?
maybe you have to call Stop() on the audiosource, assign the clip, then call play?
I'm trying to think about how that would fit into my code. 
hmm well you have to figure out when you want one music to stop and the other play, is it right when you start loading, when loading finishes
to keep it simple, maybe just inside your "load scene" function, you assign the clip that you want there
My biggest problem is figuring out how to get the clip from AudioManager's Music Sound's clip.
Thats hard to say
public function called SwitchMusic() that you call from the load scene function?
SwitchMusic() would be in the audio manager
where are you storing it?
do you have a List<AudioClip> in your audio manager?
and you are dragging and dropping all the audioclips from your assets into the inspector
Yeah
then you have a reference to all the audioclips in audiomanager, so you could just do SwitchMusic(int musicIndexInList) for example
OH! Wait do you mean, list all of them and then choose the int for example if music was 15???
Then change the audio clip for 15
yep that way the scene loader doesnt need a reference to the audioclip
OwO
although you could also do it that way, you can make that list public and have the logic directly in the scene loader if you wanted
its just cleaner to have all that logic in the audio manager
and theres other ways to be cleaner too but you can clean that up later
How to make c# errors in another thread be thrown into debug console?
because when error occurs there (for example, div by zero) the thread stops and it doesnt print anything into the console
they have to be in a try/catch block
im not sure if try/catch works in a thread you created yourself actually, if you use C# Tasks you can get the exceptions with try/catch
i havent seen if theres a method to automatically do it nowadays that popped up but when i checked a while back you had to do that
I instantiate the same Canvas prefab twice at runtime, one time it has the World Space property [1], which does not appear in the original prefab (which is the desired result, not sure why it works that way). In the second case, it stays as the prefab, with missing options in the Canvas component [2].
(click the images, not sure why discord sized them like that)
Hm, maybe it doesn't show all options if the canvas is a child of another
Which would make sense as only the root can dictate where it's placed and how it's rendered
hi,
is it possible to hide/show some properties on the editor based on enum or a bool ?
If you have NaughtyAttributes, you can use a conditional attribute. Else, make your own custom inspector
That was exactly the issue, thanks!
thanks is there is any resource to the conditional attribute ?
NaughtyAttribute's docs, online
Thanks , after looking at it and I've decided to give a chance to the CustomEditor :), thanks for the help ❤️
I suggest just using naughty's
There's a lot of attributes among the conditional attribute that you'll find useful
That and it does supply you with some functionality for custom inspector stuff if you do want to create some later
Anything wrong here at first glance?
I guess I'll order them in paint, Discord messes it up.
Canvas positions should be set using the RectTransform's anchoredPosition, so your anchoring preset is respected
I'll check, better version (since i already did it)
(Discard if the target position is translated from world space to screen space)
Btw I call it an anchor but it's not really one
Not sure if relevant
But those are all transform.position
It's the whole canvas that's moving
You'll have to explain what you want to do, and what those variables are
Those are where the world space canvas will be placed
Hi, I have a simple question: I have a player with a Rigidbody which in turn has multiple colliders under it (a few for general collision and one to check if it's feet are grounded). I want to know which one of the colliders was hit in OnCollisionEnter(Collision collision). Looking at collision.collider is not right since it's just the thing I'm colliding with, not my own collider. Do i really need to give each collider a separate kinematic Rigidbody and MonoBehaviour just to know which collider generated the event?
I guess my thing is hard to understand as is, will keep on testing things!
I think all it was was me changing .position instead of .localPositon
i think you can do collision.GetContact(0).thisCollider
or iterate through all the contacts
@dusty badger Ah thanks! I've always just assumed GetContact was to get a basic Vector3 impact point for some reason. I usually don't work too much with gameplay code 😅
What is the best way to debug how a certain list in my code is losing references to game objects?
hey so I just updated my game to newest version of unity and now Im just getting this error message and dont know what it means or how to fix it
I have a "scope" list in my GameManager containing all active game objects of a certain type, and for some reason it keeps losing references to one specific type of game object shortly after they're instantiated. I'm not familiar enough with VisualStudios debugging, help would be appreciated.
Algo 3602 Ah thanks I ve always just
I think u can just ignore that, u can restart the editor if u want and it only really becomes a problem if it continues to come back
ya ive restarted multiple times and its been happening for a few days now
i cant delete the line of code or anything either
Have u tried deleting your project's library folder?
