#archived-code-general
1 messages ยท Page 143 of 1
Just coming back to this now that I have it working https://img.sidia.net/ZEyI5/KOjotIQA17.jpg/raw on 2023.1.0b20 it works, guess just not updated for the .3f0 release yet
Thanks, that works.
i remember i hooked these into some binding context, but it should pick those up automatically
how did you feed it into serializer?
I have a GameData class that gets serialized, which stores a reference to the Vector3
look above
I had to add this serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;, but yeah.
ahh
yup cause it errors
i remmeber this
I am having issue with Singletons - I followed https://gamedevbeginner.com/singletons-in-unity-the-right-way/
The issue right now is the starting Instance, am I supposed to just slap it onto an empty?
Doing that would work for that one scene, but I need the Singleton in at least one other Scene.
Putting the Singleton into DontDestroyOnLoad needs a point where I initially create it, which does not exist currently - and would fuck around again with static references.
The singleton holds the data needed for perks and status effects.
Any suggestions on what to do?
I assume your game must have a starting scene? You just instantiate your singletons in that scene and mark them as don't destroy before doing anything else
If your other stuff is referencing it statically, you use FindObjectOfType instead of a static reference
Every game needs a menu scene, gotta have one anyway, no reason to build your game around the assumption that there won't be a scene
hey anybody knows how to change parameters at runtime for posteffect volumes for URP?
depends which ones
sometimes is worth more to make a new profile and fade weight in/out with a separate volume just for that effect
you can also script the editor to always go in playmode from that scene first and load the currently opened one additively
when you press play
not really
just want a red vignette when getting hit
tried using this but it wont work , maybe you approach is easier
public static void ChangeVignetteTo(Color newColor)
{
Volume volume = FindObjectOfType<Volume>();
if (volume != null && volume.profile.TryGet(out UnityEngine.Rendering.Universal.Vignette vignette))
{
instance.m_Vignette = vignette;
}
if (instance != null && instance.m_Vignette != null)
{
instance.m_Vignette.active = true;
instance.m_Vignette.color.Override(newColor);
// volume = PostProcessManager.instance.QuickVolume(0,
100f, instance.m_Vignette);
instance.Invoke(nameof(ChangeVignetteToBlack), 1);
}
else
{
Debug.LogError("Instance or Vignette is not set!");
}
}```
I think its better to get the start scene out of the way now - while I have a reason not to procrastinate on that
anyway no reason to do all this
just make a separate profile/volume just for the hits and fade the weight in
all this extra is useless imo
I agree but I have a profile for the night and for the day I guess I will swap depending on the time
you're not swapping anything
you layer it ontop
give it a higher priority and it will overlay night/day profiles just for hits
love it thank you so much @potent sleet
I've been working on a dungeon generator and am now working on visualizing it in game the way I've been doing so seems to me like its very inefficient. The dungeon is a grid and each cell in the grid has a few bools that store if its part of a room or a hallway, a door or a wall, ect. and the way it currently works for rooms for example it checks if a node is part of a room then gets that nodes neighbors and if say the neighbor above is not part of the room and the one bellow is it makes a wall. but it feel like doing this for every node is slow especially since it like a 200x200 grid.
if (point.isCorner)
{
rotation = 75;
spriteToSetTile = sprites[floor].wallCornners_1[Random.Range(0, sprites[floor].wallCornners_1.Length)]; ;
if (neighbors[1].partOfRoom && !neighbors[1].halway && neighbors[3].partOfRoom && !neighbors[3].halway)
{
rotation = 90;
}
if (neighbors[1].partOfRoom && !neighbors[1].halway && neighbors[2].partOfRoom && !neighbors[2].halway)
{
rotation = 0;
}
if (neighbors[0].partOfRoom && !neighbors[0].halway && neighbors[2].partOfRoom && !neighbors[2].halway)
{
rotation = -90;
}
if (neighbors[0].partOfRoom && !neighbors[0].halway && neighbors[3].partOfRoom && !neighbors[3].halway)
{
rotation = 180;
}
}
Have you measured how long it takes?
no not exactly
If you're worried it's too slow, measure it and find out. Use the profiler or a Stopwatch.
The Stopwatch class, that is not a physical stopwatch.
idk how advanced this is but i wanted to know if its possible to have a the head of a rig look in the same direction the camera is looking?
not very advanced. And ofc is possible
if you have a rig it's even easier , with Animation Rigging package with IK
but you can do it ofc with anything like LookAt or LookRotation or /we
If you rotate it manually make sure you clamp rotations unless you want your character to break it's neck everytime you look to far up, down or else
Has anyone else had issues with the editor not deserializing their serializedproperties? I recently deleted all the asmdefs in my project and now the serializedproperties show as blank, although the data still exists in the .asset file
guid matches?
monoscript asset/ ref guid
theres also "type" of reference
0-3 i think
when i bumped into something similar i ran string replacement on metas to fix similar issues
Is there a way to get the enumerable that a transform returns and then do a linq statement on it? ie we can do foreach(transform chil in transform) but I can't do transform.Where(...). is there a simple way to do this?
Can you just cast the transform into a IEnumerable ?
public class Transform : Component, IEnumerable
good call lemme test
the use in the foreach implies that there's an implicit cast predefined, so i'm surprised it doesn't work implicitly with Linq.
Yeah, not sure why also.
alas, it doesn't play ๐ฆ
it's not inheriting from IEnumerable since you don't inherit an interface, you implement it. interfaces are not inheritance.
yeah,
it's so you can do:
foreach (Transform child in transform)```
I see, thanks
transform.Cast<Transform>().Where(โฆ)
.Cast<IEnumerable<Transform>>()?
It is shame that it does not implement IEnumerable<Transform>. You should be able to workaround with Cast
No
casting Transform... back to Transform?
Cast is part of linq and should take element type
It casts elements of collection
IEnumerable yeah whoops.
you ever work on something for like, 20 hours, and the final product is like 35 lines, and you feel like, damn.
yes
Brainstorm properly for a few days. When you're finally implementing it, do it once - do it right.
If you're lacking knowledge to solve the problem, you'd study this during the brainstorm phase.
"a few days" is a large leeway - take however less time you're needing but be near certain you can solve the problem to be productive. Exposure to creating more games can only help you - you'll be repeating a lot of behavioral practices.
I am working like 2 hours and I think without any stops, but then I just think about what I've changed in my code..
and it's probably almost nothing in 80% situations
and I think that I'm really so slow
because I am also interapted too easily
dunno why I do say it though
Hi! I'm trying to check that, if given an array of materials (items in crafting slots) there's a match with a predefined array of materials (recipe). I tried with this code but it's always null even if I know that the arrays match, and the Debug.Log just logs the first element of the recipe. Any input?
What is CraftMaterials?
show the definition
Just an enum
I would def use SO for this usecase
@eager yacht
Sorry for ping, I just wanted to say you that I have solved that issue with textComponents and thought that you may be interested in what was wrong.
After debugging both your and my scripts, I have realised that TMPro is just done badly and has some issues that it shouldn't have. So it was "randomly" making more lines than needed and also changed TMP_Text's rendered height to ~2100 even when not needed. Probably that's not possible to change without doing smth in built-in classes, also that's not the best idea with my level of knowledge unless I wanna waste my time even more.
So I have just made it to change textComponent when its rendered height is changed (with prevHeight) and when its width is set to maximum (max is e.g. 950 and current width is e.g. 939 so that it cannot add one more character, cuz its width is too big (> 11 in our case)).
https://www.nombin.dev/qfxbenleeg
That's a part, where textComponent is changed by assigning text (you have seen it already). I have a lot more to do though, that's not very interesting to struggle with TMP_Text.
I think I should also catch input with new Input System, cuz it's more efficient. Thank you for your help one more time!
If you are talking to me, _craftables is an array of SO ๐
oh lol then idk why even use the enums array to make recipes instead of array of SO lol
๐คท
I do have Items SO that I could use instead of the enum but i figured I wouldnt need all the info data, just what item it is
eg I typically do it this way
Thing is my materials are not just materials and have more data the it isn't used in the recipe
void CheckAllIngredients()
{
if (CurrentIngredientsAdded.Count != RecipeIngredients.Count) return;
if(CurrentIngredientsAdded.Count> 0)
{
bool same = CurrentIngredientsAdded.ToHashSet().SetEquals(RecipeIngredients);
if (same)
{
Debug.Log("Make output");
MakeOutput();
Clear();
StartCoroutine(TimedRefresh());
}
else
{
Debug.Log("Not Yet Completed");
}
}
}```
I will try another approach tho
That's what matters
why am I getting this error in my admob rewarded ad script "Assets\New Folder\RewardedAdButton.cs(3,23): error CS0234: The type or namespace name 'RewardedAd' does not exist in the namespace 'GoogleMobileAds' (are you missing an assembly reference?)"... I am using
I am using unity 2021.2.24f1 and admob package version 8.3.0
here is the script...
using UnityEngine;
using UnityEngine.Advertisements;
using GoogleMobileAds.RewardedAd;
public class RewardedAdButton : MonoBehaviour
{
private RewardBasedVideoAd rewardedAd;
private const string AD_UNIT_ID = "YOUR_AD_UNIT_ID";
public void Start()
{
rewardedAd = RewardBasedVideoAd.Instance;
rewardedAd.OnAdLoaded += HandleAdLoaded;
rewardedAd.OnAdFailedToLoad += HandleAdFailedToLoad;
}
public void OnButtonClick()
{
if (rewardedAd.IsLoaded())
{
rewardedAd.Show(AD_UNIT_ID);
}
}
private void HandleAdLoaded()
{
Debug.Log("Ad loaded");
}
private void HandleAdFailedToLoad(string error)
{
Debug.Log("Ad failed to load: " + error);
}
}
Anyone can help ?
Error on line 3, RewardedAd does not exist inside of GoogleMobileAds.
Examples online show using GoogleMobileAds.Api, did you mean to use that?
๐ 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.
@gloomy stirrup
yes
yea
read the posting code
ok
any solution ?
Let's do this one differently
all I have to do is using GoogleMobileAds.RewardedAd; ... but for that I dont know how to set up assemblies
ok4
Remove the using that errors, entirely
ok
Let's use your code editor's features to fix the errors
but RewardBasedVideoAd lies in GoogleMobileAds.RewardedAd; so now its showing error
ok
Yeah, now that you have the error underlined on RewardBasedVideoAd, hover over the error and click the light bulb icon that appears
It'll give you some suggestions, with hopefully one that says "using ...."
The one that says "using [something]"
Yeah so RewardBasedVideoAd doesn't exist
I can't seem to find it on their docs, is the tutorial you're using up to date?
I can only find RewardedAd
its google bard
Yeah that's clearly not the right way to code, asking an AI
can u suggets a good tutorial ?
beccause I tried on YT but got things that doenst work
ok thanks
Take inspiration on the syntax of line 128
You're missing the lambda expression symbol =>
it worked thanks
well wich method i have to call from button
LoadRewardedAd() ?
I guess you would know best? We dont know what code does.
np it worked I assigned both LoadRewardedAd() and ShowRewardedAd()
Ah just realised theres a history of chat here, my bad.
xD... well I still have one problem.. the ads is not fulscreen
xD
not a big problem
as I am just learning how to do it for my real game
but still something to be resolved
those are in the editor, so not real ads. Test on an actual device before you assume that
ok
THANK YOU ALL it worked.. and now I finally know how to do it
PlayerController(PlayerNetwork):https://gdl.space/yiqulehopa.cs
i want my gun to rotate with me normaly. but it is far away from me and thw rong way after starting the game. In the Player PreFab the gun is normaly placed
pls (im beginner so)
public class Bullet : MonoBehaviour
{
public float speed = 20f;
public Rigidbody2D rb2d;
public AudioSource sound;
void Start()
{
sound.Play();
rb2d.velocity = transform.right * speed;
}
// Update is called once per frame
void Update()
{
}
}
how can i make it so that the bullet moves based on the direction of the transform
the rb2d is the firepoint
and even though it flips when the character when i go left the bullet still fires to the right
rb2d is definitely not the fire point
It's the bullet's Rigidbody2D
You'd have to show how you spawn the bullet
Short answer is make sure the bullet is oriented properly when you spawn it
void Shoot()
{
newProjectile = Instantiate(bulletPrefab,firePoint.position,firePoint.rotation);
}
Looks good, guess your fire point isn't actually rotating
I know
and it pushes me far
You're probably rotating your character with the sprite render flipX thing
heres how i flip my character
Comes from PlayerController
void flip() {
if(facingRight && inputHoriz < 0f || !facingRight && inputHoriz > 0f) {
facingRight = !facingRight;
Vector3 localScale = transform.localScale;
localScale.x *= -1f;
transform.localScale = localScale;
}
}
that would work just fine for this
I'd guess that the fire point is not a child of the object that is flipping then
which object is flipping
X
should work then
maybe your bullet is colliding with your character
it does
it doesnt work
I have a scriptable object that stores a list an object called ShopItem which contains these attributes:
- string name
- int cost
- sprite icon
If the name is the same as the icons file name, would it be better to just do resources.load or is that too resource intesive?
For reference I have 50 items to go through
any tips
forgot to mention
the codes i provided came from different scripts
layer based collisions or Physics2D.IgnoreCollision
im talking abt the movement of the bullet
You need to explain the scenario in which you are loading this thing and the general access patterns for that question to have a useful answer. What are we comparing Resources.Load with?
So I intend to have a scroll view with a series of buttons lets say 50 of them. I want to load the data for each button which will display its name (label), cost (int), and icon (sprite). I intend to loop through a scriptable object when I load that scoll view which will contain a list of those objects (ShopItem contains name, cost, and sprite). I can either keep the sprite attribute in that scriptable object and load it when I loop through the scriptableobject and pull it to use it as an icon for that button OR use the name of that index and do resource.load for that sprite instead
Im thinking resource.load is resource intesive if I have to load like 50 different sprites at once so im asking here to double check
@leaden ice
rb2d.velocity = transform.right * speed;
how can i change this so that it doesnt just travel "right"?
Insert any direction in place of transform.right . . .
what i mean is
@rain minnow make the bullet move to the direction that the character is facing i mean
like if the character faces left
the bullet should fire to the left not the right
that's what i mean
transform.forward (I think)
Your character forward should then always be transform.right in 2D
Oh its 2D
Instead of flipping the sprite only, you rotate 180 on Y it always faces transform.right
i switched back to rotate
it fixed the issue
thank you


Look into sprite atlas
I need help with an issue. I created a trigger that loads in a scene async additively but the scene loads multiple times creating duplicates, how do i stop this from happening?
check if you've already tried loading it
What do you mean
Like a bool to track if you've already tried loading it, or Scene.isLoaded
K ill try it tomorrow when i go on my pc
the bullet should come out of a weapon, no? just use an empty GameObject as a spawn point that points correctly out the weapon and use that when instantiating (or positioning) the bullet. then you move using the bullet's forward direction when firing . . .
Mathf.Atan weird rounding to -90.0f
Hi everyone. I feel like I am missing something really basic, but I need to add a force to a 2D object. This is the code I am using, but no force is added to the object and unfortunately I don't get any errors to guide me where to look. I did try to Debug.Log the enrb and it returns the name of the GameObject followed by 'UnityEngine.Rigidbody2D' which leads me to believe maybe I'm going the wrong way around the AddForce thing...
public void OnTriggerEnter2D(Collider2D collision) { GameObject otherObject = collision.gameObject; Rigidbody2D enrb = otherObject.GetComponent<Rigidbody2D>(); enrb.AddForce(new Vector2(50f, 0), ForceMode2D.Impulse); }
bet
I don't see your log in the code illustrated? 
The purpose of logging here is to see if the function is occurring.
Oh yeah, I removed it so you could see only the relevant code. The logging fired as expected
Anyone have any thoughts on the free kinematic character controller on the asset store vs using the Unity character controller and writing your own movement code? I'm curious how the kinematic controller on the asset store compares since it is totally independent of the CharacterController component
I would evaluate the kinematic CC asset before Unity's PhysX CC. Certainly comes with more examples to get you going.
Yeah, I've already been looking at it and through the code as well. It's an interesting approach to character movement. I'm just curious if anyone has ever benchmarked both and compared, or if there are any thoughts on the flexibility of each?
Thanks btw
void PadROtate2()
{
Vector3 rotationInput = new Vector3(p_input.rotationAxisX, 0f, p_input.rotationAxisY);
Quaternion targetRotation = Quaternion.LookRotation(rotationInput);
Quaternion deltaRotation = Quaternion.RotateTowards(rb.rotation, targetRotation, rotationSpeedForPad * Time.fixedDeltaTime);
rb.MoveRotation(deltaRotation);
}```
Guys sorry i dont understand. my character resets back to its original rotation position after i rotate my character using my stick? why? i just want my character to move according to where my stick got pushed ๐ฆ
Your target rotation is entirely derived from the input rotation, you don't rotate by that amount, you're moving towards that value
if the input is 0, then the target is 0
Anyone knows what is this? https://docs.unity3d.com/ScriptReference/PlayerSettings.Bratwurst.html
Hello I been trying to create an ability class that o can create abilities with. The ability class works as I am able to do things with it (Call animator triggers, change the gravity of my player. Instantiate objects) however I have a part which I want to apply and x velocity to the rigid body. I can see in the inspector that the player is receiving the velocity as it updates there but the position does not move at all. I do Al my player movement in another script so I worry that may be the cause of my issue. Any ideas on how I can get the dash to work?
No errors
Just a rigidbody.add velocity
I see the velocity being updated in the inspector for the duration of the ability
But the player dosent move
Currently implementing Instance Pooling into my project, what's the best way to tackle the system?
I'm leaning towards either a Master One that handles all the pools across a scene or an Object Specific one that looks after the pools for a singular object (All the objects that are instantiated by a player for example).
oh ok! thanks so i re-edit like this
void PadROtate2()
{
float rotation = Mathf.Atan2(p_input.rotationAxisX, p_input.rotationAxisY) * Mathf.Rad2Deg;
Quaternion targetRotation = Quaternion.Euler(0f, rotation, 0f);
rb.MoveRotation(Quaternion.Slerp(rb.rotation, targetRotation, rotationSpeedForPad * Time.fixedDeltaTime));
}```
but still same problem ๐ฆ am i still not get it right?
Again, you're moving to targetRotation, which is entirely based on your current input values
how can i add to the z coordinate of a 3d object inside the update method so its always moving upward?
something like
void Update() {
//in here the z coordinate goes up by one
}
transform.position+=transform.forward;
ok
also would this work transform.position += new Vector3(1 * Time.deltaTime, 0, 0);
but change it to z axis
pretty much
To be clear, Z is forward
transform.position+=transform.forward*time.deltatime;
Up in Unity is the Y axis
OHH okok i think i know what u mean. Sorry but can you give me another hint pls on what i should change or take note of? Im still kinda lost
How should I write this string format so it looks like a 00:00:00 timer
$"{hours:00}:{minutes:00}:{seconds:00}" iirc
No need for string.Format
Seems to work, thanks
how is the movement been done in the player script?
is that the rigidbody.add velocity you mentioned or is that the ability?
I'm getting a transient missing reference exception when I start my project; within a simple foreach(Transform t in transform). It only sometimes occurs, and the object which is missing (UI_Hand) is never cloned or destroyed in my project. This is also happening on the first iteration, and it's just the t that's unset. It seems to operate most consistently when it's the first time I've hit play after loading unity; or after a full reload.
Has anyone heard of this happening or know why it does? UI_Hand is a plain gameObject that sits in my hierarchy.
The issue is to do with hand not being assigned in the inspector, not the foreach loop
No - the error line is on the reference to transform.
Unless transform is declared as UI_Hand transform, it's not.
er, it's the transform of the gameObject - the built-in unity reference.
This error also only happens sometimes, not every time.
Then you are mistaken and the error is not coming from there.
even if I comment out those lines; the simple Debug.log(transform) is throwing the Object has been destroyed - not even a null result.
the Debug in Start() works however.
Then OnSetActivePlayer is being called even when your Component is destroyed, how are you calling that function?
It's connected to an event. But there's no code that destroys the component or GameObject. It gets called from an event that is Invoked in another GameObject's Start().
Is your event static?
oooh yes it is
Then you need to properly unsubscribe from it when your object is destroyed
hmm that makes sense but it's never being destroyed. And we're not running into the exception until we reach the Debug - ie, the method is executing (like this string Debug.log)
I guess it would make sense if it's persisting between Play sessions?
huh
Especially if you have Configurable Enter Play Mode enabled https://docs.unity3d.com/Documentation/Manual/ConfigurableEnterPlayMode.html
I can't control unsubscribe because I'm arbitrarily ending play mode frequently during testing. Is there a way to make sure a System.Action resets itself on Play Mode?
Why can't you use OnDestroy?
does that get called when an exception is thrown or I dump out of play mode?
It'll get called when you exit playmode
hmm. I'm thinking turning off Enter Play Mode Options may be the culprit.
That'll certainly do it. You can also unsubscribe everything from your event in the callback mentioned on this page https://docs.unity3d.com/Manual/DomainReloading.html
which should be easy
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void Init() => s_MyEvent = null;
I do it with the input add horizontal, and in my fixed update thereโs a rigidbody add velocity similar to the one on the ability
I use a goodly number of static events... and I turned off domain reload because getting into play mode was taking an unreasonable amount of time (although upgrading to latest LTS seems to have helped a lot). I wonder if that reload is so slow due to the high (not really - dozens, not 1000s) of static events?
๐คท I use CEPM always ๐
CEPM?
The last page I linked documents static events and recommends using Application.quitting, either works
so just addforce? not using velocitychange?
Configurable Enter Play Mode
Yea addforcw
If I remember correctly, I left my house just very recently so I canโt check my code, Iโm just going off memory.
assuming it is AddForce, have you tried applying a huge number to the force just in case?
Thanks for the tips. Never would have guessed the static events were 'cacheing'
the only thing that comes to mind for why force isn't applied is when the velocity is overwritten
They're generally a source of memory leaks in projects regardless of this, so you've gotta be careful when you use them that you're unsubscribing if your game could ever resubscribe (like when you restart the game via its menu)
I think thatโs the case too, since oneโs itโs fixedupdaye and oneโs normal update?
I canโt really test what you suggest right now, do you mind I message you later when I get home? So I can show you what I got?
yeah sure. Though my suggestion though is pretty straught forward. It's just to see if enough force is being applied.
is this an issue with all forms of events? I use System.Action<T> instead of UnityEvent
the other thing I can think of is the player's rigidbody isn't receiving the force but We'd need to see more of your script to know why
Yea but the fact you came up with that means your smarter then my puny new programming brain and sometimes a second opinion really helps
Appreciate it. Thanks
It's an issue with anything that's static that contains a reference. It's just easy to forget that a delegate (eg. Action or UnityEvent) is really just a fancy list that refers to a method and anything that it requires to be captured
makes sense
Hi, so, I'm coding a sound menu thingy for ym game and for some reason only the playerpref.get that is in the first line gets correctly issued to the sliders, what could be the reason and how can i fix it?
public void LoadVolumeLevels()
{
uiSfx.value = PlayerPrefs.GetFloat("UI-SFX", 1);
gameSfx.value = PlayerPrefs.GetFloat("GameSFX", 1);
mainMenuMusic.value = PlayerPrefs.GetFloat("MainMenuMusic", 1);
highlightSFX.GetComponent<AudioSource>().volume = uiSfx.value;
selectSFX.GetComponent<AudioSource>().volume = uiSfx.value;
inGameSFX.GetComponent<AudioSource>().volume = gameSfx.value;
MenuMusic.GetComponent<AudioSource>().volume = mainMenuMusic.value;
}
start printing things with Debug.Log to figure out what's going on
so like, put a debug.log after every playerpref line?
I tried this and i got all the in the console
public void LoadVolumeLevels()
{
uiSfx.value = PlayerPrefs.GetFloat("UI-SFX", 1);
Debug.Log("uisfx");
gameSfx.value = PlayerPrefs.GetFloat("GameSFX", 1);
Debug.Log("gamesfx");
mainMenuMusic.value = PlayerPrefs.GetFloat("MainMenuMusic", 1);
Debug.Log("menusfx");
highlightSFX.GetComponent<AudioSource>().volume = uiSfx.value;
selectSFX.GetComponent<AudioSource>().volume = uiSfx.value;
inGameSFX.GetComponent<AudioSource>().volume = gameSfx.value;
MenuMusic.GetComponent<AudioSource>().volume = mainMenuMusic.value;
}
Print out the values of all these variables and what's coming out of PlayerPrefs and make sure it all matches your expectations
ok
this is pointless
print out some actual information
this tells us only one thing - that the code is running
public void LoadVolumeLevels()
{
uiSfx.value = PlayerPrefs.GetFloat("UI-SFX", 1);
Debug.Log(uiSfx.value);
gameSfx.value = PlayerPrefs.GetFloat("GameSFX", 1);
Debug.Log(gameSfx.value);
mainMenuMusic.value = PlayerPrefs.GetFloat("MainMenuMusic", 1);
Debug.Log(mainMenuMusic.value);
highlightSFX.GetComponent<AudioSource>().volume = uiSfx.value;
selectSFX.GetComponent<AudioSource>().volume = uiSfx.value;
inGameSFX.GetComponent<AudioSource>().volume = gameSfx.value;
MenuMusic.GetComponent<AudioSource>().volume = mainMenuMusic.value;
}
ok so - does this match with your expectations?
looks like you have set them to 0 somewhere
but its weird, if i put the lets say gameSfx.value = PlayerPrefs.GetFloat("GameSFX", 1); line first, then i get 1 on that
Have u actually set them to 1 anywhere, it will only be 1 if it doesnt exist from your code
The number you provide is a default value if it doesnt exist
yea but its not 1, and i didnt set them anywhere else
so it should be 1
the fact that it is returning 0 means you set it somewhere
ill send the whole code, wait
although you are making another mistake here which is printing gameSfx.value instead of directly printing the playerprefs return value
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class SoundManager : MonoBehaviour
{
public GameObject player;
public GameObject highlightSFX;
public GameObject selectSFX;
public GameObject inGameSFX;
public GameObject MenuMusic;
public GameObject musicInGame;
public GameObject musicPowerUp;
public GameObject musicDeath;
[Header("Volume Sliders")]
public Slider uiSfx;
public Slider gameSfx;
public Slider mainMenuMusic;
public Slider inGameMusic;
void Start()
{
LoadVolumeLevels();
musicDeath.SetActive(false);
}
// Update is called once per frame
void Update()
{
if (SceneManager.GetActiveScene().name == "InGame")
{
if (player.GetComponent<Movement>().inPauseMenu == false)
{
Death();
}
MenuMusic.GetComponent<AudioSource>().mute = true;
}
}
public void ChangeUISfxVolume()
{
highlightSFX.GetComponent<AudioSource>().volume = uiSfx.value;
selectSFX.GetComponent<AudioSource>().volume = uiSfx.value;
SaveVolumeLevels();
}
public void ChangeInGameSFXVolume()
{
inGameSFX.GetComponent<AudioSource>().volume = gameSfx.value;
SaveVolumeLevels();
}
public void ChangeMainMenuMusicVolume()
{
MenuMusic.GetComponent<AudioSource>().volume = mainMenuMusic.value;
SaveVolumeLevels();
}
void Death()
{
if (player.GetComponent<Movement>().inPauseMenu)
{
//make some kind of tunnel sound effect
}
if (player.GetComponent<Movement>().isDead)
{
musicInGame.GetComponent<AudioSource>().mute = true;
musicPowerUp.GetComponent<AudioSource>().mute = true;
musicDeath.SetActive(true);
}
}
public void SaveVolumeLevels()
{
PlayerPrefs.SetFloat("UI-SFX", uiSfx.value);
PlayerPrefs.SetFloat("GameSFX", gameSfx.value);
PlayerPrefs.SetFloat("MainMenuMusic", mainMenuMusic.value);
}
public void LoadVolumeLevels()
{
uiSfx.value = PlayerPrefs.GetFloat("UI-SFX", 1);
Debug.Log(uiSfx.value);
gameSfx.value = PlayerPrefs.GetFloat("GameSFX", 1);
Debug.Log(gameSfx.value);
mainMenuMusic.value = PlayerPrefs.GetFloat("MainMenuMusic", 1);
Debug.Log(mainMenuMusic.value);
highlightSFX.GetComponent<AudioSource>().volume = uiSfx.value;
selectSFX.GetComponent<AudioSource>().volume = uiSfx.value;
inGameSFX.GetComponent<AudioSource>().volume = gameSfx.value;
MenuMusic.GetComponent<AudioSource>().volume = mainMenuMusic.value;
}
}
PlayerPrefs.SetFloat("UI-SFX", uiSfx.value);
PlayerPrefs.SetFloat("GameSFX", gameSfx.value);
PlayerPrefs.SetFloat("MainMenuMusic", mainMenuMusic.value);```
you are setting the playerprefs here
But you've set it at one point
and you've never touched them in your life?
i mean, yea ive touched them lol
but i delete the registry after every try
so i should be getting default on every run
which registry
you shouldn't be manually touching the registry if that's what you're doing
there's an option in the unity menus to reset the editor playerprefs
You could also just add a temporary code to test it if you wanted to force values to be 1. As long as you remove it after
you might not have been deleting the right one
there's a separate one for the editor
Anyway you should look at this
ok
your slider could just be configured wrong
ill get back to u after a while
e.g. mx vlue of 0 or something
gotta do something
public GameObject highlightSFX;
public GameObject selectSFX;
public GameObject inGameSFX;```
Highly recommend using direct AudioSource references here too
no reason to use GameObject for everything
just makes the code uglier with all the GetComponent calls
Yo, gonna ask smth, how do you stop an asynchronous function? I know of CancellationTokenSource but wondering for other ways. 
hi, sorry for the ping but turns out this was the issue afterall
thanks!
Hi again, any idea of how to implement a master sound control for this?
Use a bool and return if the bool is true.
I guess there's no other ways. ๐คท
is there any way to control the weight of an animation like you can control the weight of layers from code?
With a blend tree perhaps.
never heard of a blend tree
Look it up. It's often used to blend between different similar animations, like Idle/Walking/Running.
Hello, I just cant change my sprite pixels per unit, sprite mode etc, no longer. The "Apply" button just is constant gray and not being able to be pressed. Even though I didnt change anything.
btw restarting unity sadly doesnt fix it
It would be gray if you didn't change anything, since there's nothing to apply...๐ค
Yeah i know, but I did try to change the pixel per unit
it just doenst let me apply it
Take a screenshot of the asset selected with the project and inspector windows visible.
Changed the Sprite mode from single to multiple and ppu to 16. But I can change the Compression etc. When I then apply only the Compression changes but nothing else
it feels like a sort of "project locking mechanism"
It's impossible to stop functions in general, unless they implemented a way to break out of the method
The only exception (pun not intended) is exceptions, which is why cancellation tokens throw an OperationCanceledException in basically all cases of c# internal methods when you cancel a passed cancellation token.
Perhaps because it's a Psd? Try saving it as PNG and see if it changes anything. Either way, how is that code related?

You could argue that source generators are the second exception, but even those would inject a return; somewhere. A good example is probably EF, which does it in order to gather the relevant dependencies and such when you invoke migrations or anything else that requires it (I'm not actuall sure how they did it but that is the only explanation)
Useless info if you never used EF of course
Nope already PNG
So that bears my question, why don't you just use a cancellation token? It was literally made for it
Then no clue, but try asking in #๐โart-asset-workflow instead.
its also on every other sprite not just that one
Even Unity2023 adds support for it
Yeah i will. 
does anyone know if there is a way to have an array of vector3s in shadergraph ?
or use an for loop
i need to add alot of variables to make my gersnerwaves look more realistic
array of vectors sounds like a texture
however there is mat.SetVectorArray()
i assume there is a way
thx
@.cache do you know how to convert vectors to a 1d texture ?
in c#?
yeah
just dump as color into a buffer, feed into a texture through SetPixels
...
there may be more optimal api now
speak english please
i did
if you have concrete questions specify what exactly you dont understand
because i wont be guessing what is unclear to you
Does anyone here work with Unity VR? I have some questions about Input controllers for VR applications.
input.getAxis should work (Apologies if that's malformed, I don't know C# syntax.)
And input.getButton
Look in Project Settings under Input to get the names, VR inputs usually start with "XR" or "XRI"
I want to add keyboard inputs to my VR simulations. My VR controllers are working but I want to use keyboard input to load/reset scenes.
Okay, input.getKey should still work
I have tried using Input.GetKey doesn't work because I tried using this in the if condition but it doesn't give any output with Debug.Log
Does anyone have any resources or good pointers on where to look into circle collision resolution? I.e. If I have fifteen circles overlapping in one step, how to push them away from oneanother such that they no longer overap
Hm, is Debug.Log set up to trigger with true and false?
No, If on KeyCode.Space
I wanted to learn how it was done, but was getting my search results clouded by hashing tutorials for the similarly named collision resolution
you will be essentially doing physics solver
iterations, depenetration, iterations, depenetration .. repeat every frame until there are no collisions
Awesome thank you!
@devout harness or you know
you could just use Bepu
straight up
assuming you cant use physics 2d for some reason
I'm just exploring the process-- I figured I'd finally sit down and examine how it's done and try my hand at a worse one, but was very quickly stumped on the issue
i understand
I find it such an interesting problem, it seems extremely simple intuitively as a human but programatically is a nightmare
yes and its not solved yet
Ooooo interesting- there's not a fully optimized solution?
So, I'm in a weird situation, I'll definitely want to learn C# at some point soon, however I already know most of it, except for syntax.
physics engines i know will choke due to combinatorial explosion when there are too many colliding bodies
Ahhhh okay, I take it that's a huge reason why fluid simulation is reserved for things like thousand dollar software on million dollar server farms at the highest quality level?
optimizations there are based on fields afaik
(I use VS, which is how I know a lot of stuff minus syntax.)
static structures which dont require per entity resolution
Flow rambles about learning C# (And some malformed C# code)
I am using the new Input system, and am trying to have adaptive Text like Press X to Y that changes depending on which Control Schema is Active. I currently get the text by action.ToInputAction().GetBindingDisplayString().ToUpper() where action is a InputActionReference. I however only get the text for one of the schemas. Is there a way to prefer one Schema over another that if it is available I get the corrosponding label? If that is not possible is there a way to print all possible bindings?
EDIT: found a way to get all binding using action.ToInputAction().bindings - with that you can then do binding.ToDisplayString() to get what I needed
wtf do they mean missing
i didnt even delete that
there is no script that delete Wpn object
Hi all! I'm trying to toggle a GameObject's material transparency on the fly, via code, analogous to what would happen if I were to switch the "Surface Type" from "Opaque" to "Transparent" in the first screenshot. Any ideas on how to do it? I tried it via the code you see in the second screenshot, but that had no effect.
Hello, can you help me please?
I am still trying to understand how the profiler works but I am not managing to understand where is the issue
did you switch to hierarchy mode?
Yes
But I noticed that I can't try the profiler in build because it's an android game and unity doesn't detect my phone idk why
Here are some screenshots of the profiler, and of the hierarchy of the CPU
hierarchy is sorted by cost
press arrows
expand
find whats eating up your cycles and generates most garbage
if its yours optimize it
if its not, google solutions or use different plugins
I noticed that sometimes over 50 percent is taken by URP, is it normal?
dont know
!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.
When the player touches an invisible trigger it loads a map but whenever it is triggered the map loads multiple times (I have very little skill in coding atm and i dont know how to avoid unloading the player when switching scenes)
Async loading functions take time, you need to make sure you don't do the same thing multiple times, try disabling or destroying the loading trigger after starting the async load.
how do i destroy it
void Update()
{
if (axeReturn)
{
if (time < 1f)
{
axeThrow = true;
rbAxe.position = QuadraticBezierCurvePoint(time, oldPos, curvePoint.position, targetAxe.position);
rbAxe.rotation = Quaternion.Slerp(rbAxe.transform.rotation, targetAxe.rotation, 50 * Time.deltaTime);
time += Time.deltaTime;
}
else
{
ResetAxe();
}
}
}
[Command]
public void ReturnAxe() //AnimationEvent
{
RpcReturnAxe();
}
[ClientRpc]
void RpcReturnAxe()
{
rbAxe.gameObject.GetComponent<AxeController>().activated = true;
time = 0f;
oldPos = rbAxe.position;
rbAxe.velocity = Vector3.zero;
axeReturn = true;
rbAxe.useGravity = false;
rbAxe.isKinematic = false;
}
I couldn't sync the ax's return
Destroy(this);
will it come back after the scene is reloaded?
Yes
kk
You could also use the non-async loading methods, which don't require unloading and don't take time, this will cause your game to pause while loading but you can probably deal with that for now.
How do I find the correct field of a material if I want to edit it?
For instance I am making a builder with a preview of what ur building so I want to change the surface type to "Transparent" but I can't remember how to find the key...
mat.Set???("Key?", Value)
I recall there is a window somewhere that shows all the information of a material?
Ehh just swap materials
I think that depends on the shader and is probably not build in Unity - an easy way to switch between the 2 is use a different material, and edit the .PNG to be 50% transparent instead
I am not great with shaders tho so don't mark my words ๐
I want to maintain all the other settings like normals, smoothness, metallic, height, etc... etc... So I can do it that way but I'd need to then populate all the fields of a new material
Like this
previewMat.SetTexture("_BaseColorMap", newMats[ii].GetTexture("_HeightMap"));
previewMat.SetTexture("_HeightMap", newMats[ii].GetTexture("_HeightMap"));
previewMat.SetFloat("_DisplacementMode", 2);```
I rather do that ^ but just 1 field... but I forgot how you get it
in unity what would take more peformance.
Using Vector3.Distance to check if a player is near enough on 100s of objects, or using a physics.overlap sphere to check if the player is near enough on 100s of objects
Profile and find out
I just want to adjust the alpha value of the base colour but that requires changing the surface type :l
things like "_BaseColorMap" and etc are all exposed somewhere I believe? I just can't remember where
Why wouldnโt it be easier to swap to a material you already adjusted settings to prior to run
Because that means I'd need 100's of extra materials I make and they would need to be tied to all the objects so they can be convereted
Highly depends. If the sphere overlap is only overlapping maximum 10 objects compared to needing to check ALL gameobjects... However... Don't use Vector.Distance (Unless you want to know the exact distance in units) Use Vector3.sqrMagnitute instead. It's a bit quicker.
You could do it that way but yeh... I'd need to tie a preview variation to every normal material
Im just using distance and only checking when the player presses the interact key
but thanks for the tip as I am always using vector3.distance and it is a heavy hitter
Yeah, you'd need Vector3.Distance if you'd like to know the exact distance between them. But if you want to know which one is closest. Just use Vector3.sqrMagnitude. A bit quicker.
A good thing to know how "performant" something is, is to check out "Big O notation": ( https://en.wikipedia.org/wiki/Big_O_notation )
Maybe a YouTube video is better at explaining it than Wikipedia ๐ .
My problem is the other way round, its 100+ objects individually checking if 1 object, the player, is close enough to interact.
if (Input.GetKeyDown(KeyCode.E) && !open)
{
if(Vector3.Distance(servermanager.localplayer.transform.position,transform.position) < playeropendistance)
{
open = true;
Invoke("close", servermanager.boxregentime);
}
}
@thorny rock Okay from what I've read up, it seems that the editor does a bit of lifting internally when you swap the Surface type.
I think I'm going to just have a transparent "Base" material which I clone and then copy over the properties from the building I am planning to place. So similiar to what you suggested I guess? Thanks ๐
Make the problem other way around. E.g. the player has a collider (Trigger) and if that collider triggered with one of those 100's of objects, you know you are in range of one of those.
Saves you 100's of calculations each time you click on the button
Its just my playerscript is already bloated with stuff for interaction
Yeah exactly. Afraid I don't really know shaders ๐ฆ ... It's how I usually do it ๐
Then create a seperate script and attach it to the player ๐
I could have a interaction ghost script for each interactable object
Having objects check if a player is in range is pretty poor and makes scaling a nightmare though
Like you wouldn't have bullets fired and then all AI check if the bullet has hit them yet
Exactly. Thus the player script should simply check if the interactable is inside it's collider. So there's no check / caluclations at any time.
Only waiting for an event to trigger which is basically zero performance hit ๐
If you inherit from an abstract class like "Interactable", you can make different scripts like your door opening, searching something, breaking a window, etc... and then just call the ".use" function on them or something
If you do it this way, you don't have to worry about bloating your script, you can expand with it and it's efficient
By the way... I forgot exactly how but believe there is a way that you can create a temporary sphere collider and get everything it collides with? Not sure about the efficiency of it but if you have that happen when you click? That might be pretty good
Thanks for the advice. turns out serializedreferences state the assembly that they can be found in, replacing this with Assembly-CSharp fixed them all
is findobjectsoftype in awake safe?
in the "will it find all matching components that are enabled at scene load" sense
safe?
yes it scans through all your gameobjects
looks for the component
Okay, was worried there could be scene load instantiates X before Y, X awake is called whilst Y is non-existent or some other race issues
Hey everyone, in my game i have a lock where i want to scroll the ui(the numbers) infinitely. I tried with a scrollrect to reset the ui position if it is bigger than ... but when I drag i get the transition is not fluent. I thought could be a way to change the uv position of the texture. But how can I do that with the scrollrect
thank you @potent sleet
awake is always called before anything so if you have something spawning make sure it's in the scene already
you probably want to using lerping methods/ tweening
any idea on this? it throws the error
method name expected
on the line with the red underline
A few things wrong here
but I think in this instance you have rogue brackets, like you're calling a function, but that instance of ScoreboardDataClass isn't one
without that unity gives the error
cannot convert void to ScoreboardManager.ScoreboardDataClass
I also suggest taking the word class out of your class name, and very taking the word class out of the instance name
You have two instances of ScoreboardDataClass, one called scoreboardDataClass and one called scoreboardDataIndex, which is very confusing
yh fixed that alredy, but the main problem is that
can i add an empty class to a list
the method you're calling on the List called Add is returning nothing
wym
and you're trying to assign that to the scoreboardDataClass, that's why you're getting an error about voids
Do all the people with "Unity Staff" develop the engine?
No
Unity is not only made up of developers
Well yeh but if someone works at Unity for marketing, their input is a bit different is why I asked out of curiosity
Thanks for the answer ๐
Hello, wanted to ask is there anyway to have 1 animator controller be able to control 2 sets of animations?
Like I have a player and it has animations that it has a sword with and animations without it. I have some animations that are shared between but I want to swap between 2 layers (I plan to copy everything over and just change the sword specific animations to the melee ones) with like an event or a button. Would that be possible and how would I achieve that
#๐โanimation for questions about ... animation
Should I just avoid using Enum's in my monobehaviors for the purpose of cleanly selecting options in the editor? If I need to reference the enum value through the Editor and say.. cast that to a string, it doesn't appear I can. Should I instead store just a string/int on the game monobehavior and then declare the enum in the editor and somehow override the dropdown selector for whatever the enum represented in the inspector?
Just use enums
Then how do I get a string out of the enum value in the Editor?
why do you want a string of the enum in editor?
updating the name of a prefab instance dynamically to kind of denote it's type at a glance..
you can just do .ToString() on an enum
It won't work
What I dunno is how you'd get the selected enum from the inspector
I think .ToString() doesn't work if you manually set int values that are out of index
Or I could be confusing it with something else
it gives me a boxing allocation error
beacuse the enum is defined outside the editor I think
I think we need a bit more information ๐
screenshot it
Boxing allocation: inherited 'Object.ToString()' virtual method invocation over the value type instance
Windows + shift + S
Show your !code too
๐ 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.
alright, gimme a moment
Btw Xitech I just found this lol
https://stackoverflow.com/questions/56785869/c-sharp-enum-tostring-boxing-resolve-or-supress
The boxing is because Enum.ToString calls the Enum.GetValue method, which returns the underlying value as an object - hence the boxing operation. The string is a reference type so it is not boxed. And just because of the string conversion no boxing would be necessary.
Essentially, if you're just running your code in OnValidate, you can just suppress that warning, more garbage to feed the garbage collector in the editor. Not very desirable at runtime.
Supression worked
If it's under the Editor folder and using Editor dependences it shouldn't be executed at runtime anyways right?
Yeah
I don't plan on using it outside of the Editor
It might be worth swapping to a scriptable object or just an inherited type
Anyways, thanks everyone that helped ๐
public class MarkerPositionSaver : MonoBehaviour
{
public GameObject markerPrefab;
private GameObject parent;
//Marker Position Speichern
private List<Vector3> markerPosition = new List<Vector3>();
void Start()
{
parent = new GameObject("Marker Parent");
}
void Update()
{
//Taste M muss gedrรผckt werden
if(Input.GetKeyDown(KeyCode.M))
{
SetMarkerAtMousePosition();
}
if(Input.GetKeyDown(KeyCode.N))
{
DeleteMarkerAtMousePosition();
Debug.Log("test1");
}
}
private void DeleteMarkerAtMousePosition()
{
if (Physics.Raycast(Camera.main.transform.position + Camera.main.transform.forward * 2f,
Camera.main.transform.forward, out RaycastHit hit, Mathf.Infinity, ~(1 << 6)))
{
GameObject marker = hit.collider.gameObject;
if (markerPosition.Contains(marker.transform.position))
{
markerPosition.Remove(marker.transform.position);
Destroy(marker);
Debug.Log("Marker wurde gelรถscht an Position: " + marker.transform.position);
}
}
}
}
Hello i want to delete a gameobject in my unity project when i hover over it and press the key N. But my DeleteMarkerAtMousePosition Function does not work and i dont know why. the function above creates these gameobejct in my game when i press m. Could somebody help e or give me an advice where my problem is pls ?
I think the Enum class has a workaround for this, though.
Whats the best database to save data for unity besides firebase
The weight of the animation Layer should be 1 when it's name and tag name name matched. But It is getting the index of -1. Although names are correctly matches and weight is 0 still
currently in tears that unity's serialized property has no support for short or ushort values
I have a small problem I suppose.
I have a Util script that I originally made to configured to get Seeded Values from, that way, I could do a "seeded" run for my game. The problem is, it appears to be returning the same value every call, during the same frame.
Any good way to fix this?
//Sets up the spawn state to be constant.
public static void InitSeed(int seed) {
UnityEngine.Random.InitState(seed);
seededState = UnityEngine.Random.state;
}
public static float GetSeededFloat(float minInclusive, float maxInclusive) {
//Set the last state.
UnityEngine.Random.state = seededState;
//Get the random number.
float rand = UnityEngine.Random.Range(minInclusive, maxInclusive);
//Store the spawn state.
seededState = UnityEngine.Random.state;
return rand;
}
that's the whole point of a seed - to get the same value every time
or at least the same sequence of values
Right, but I'd expect it so that if I set a seed to say "1000" and get a random float between 0 and 5. The first time I call that, the value should be 2.3, and then the second time the value should be 4.2.
However in my case, I'm getting 2.3 constantly.
Shouldn't be an issue, are you changing the state elsewhere?
that would happen if you keep setting the state to the same value right before calling Range
Nope, only whenever I call "GetSeededX" values.
start Debug.Logging the seededState value
it should be changing each time
(log it before and after the Range call)
Only other thing I can think of is if you're reseeding every frame
how do i get accurate world-space mouse position delta? this is what i'm doing right now:
if (Input.GetMouseButton(2))
{
mouseMovement.x = Input.GetAxis("Mouse X");
mouseMovement.y = Input.GetAxis("Mouse Y");
cam.transform.position -= mouseMovement;
}```
but the speed seems to change depending on the size of the screen and the orthographic size of the camera (because i think it measures it in pixels)
how would i get the actual world-space mouse position delta instead of the pixel one?
mouse input is in screen space coordinates
transform.position is in world space
you will need to convert first.
And that conversion depends on exactly what you're trying to do
so just cam.transform.position -= cam.ScreenToWorldPoint(mouseMovement); ?
no wait that will certainly break
basically "mouse world position" is always a bit ambiguous
sort of maybe... under certain circumstances?
Is it a 2D game?
you pbasically need to do this
i'm trying to make drag camera movement similar to what it is in the editor
Vector2 previousMousePos;
void Update() {
Vector2 currentMousePos = cam.ScreenToWorldPoint(Input.mousePosition);
Vector2 diff = previousMousePos - currentMousePos;
cam.transform.position += diff;
previousMosePos = currentMousePos;
}```
something like that
it might actually be -= diff
not sure
probably -=
i think i tried that and it made the camera fly out into float overflow xd
but i'll try it again with this, maybe i messed it up the first time
oh yeah
uh
there's an adjustment you need to do
because the camera itself moves
Vector2 previousMousePos;
void Update() {
Vector2 currentMousePos = cam.ScreenToWorldPoint(Input.mousePosition);
Vector2 diff = previousMousePos - currentMousePos;
cam.transform.position -= diff;
previousMousePos = cam.ScreenToWorldPoint(Input.mousePosition); // reset the "previous" position to the current so next frame there is no diff if there is no mouse motion
}```
something like this
let me try one sec
ok this didn't work exactly but i added something and now it works perfectly, tyvm!
Vector2 previousMousePos;
private void Update()
{
if (Input.GetMouseButtonDown(2))
{
previousMousePos = cam.ScreenToWorldPoint(Input.mousePosition);
}
else if (Input.GetMouseButton(2))
{
Vector2 currentMousePos = cam.ScreenToWorldPoint(Input.mousePosition);
Vector2 diff = previousMousePos - currentMousePos;
cam.transform.position += (Vector3)diff;
previousMousePos = cam.ScreenToWorldPoint(Input.mousePosition);
}
}
``` - this is basically what i did
ah yeah you need to reset the positiojn when you press the button so it's not using some old one
My solution was ignoring the whole mouse button thing
Q: For testing, would this be functional for checking internet? Regardless if its hotspot or wifi. Loads offline scene if no wifi.
yes generally making a simple web request and checking the result is a standard way to check connctivity
Might actually be a good idea to have a second reliable URL you check, just so your connectivity isn't solely tied to google's uptime even if it is basically guaranteed right now
Does anyone know how i can do this with scripting
Anyone know what the included fonts are?
my usage is this
Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
Maybe a UnityEvent: https://docs.unity3d.com/ScriptReference/Events.UnityEvent.html - you can even give it a custom param with UnityEvent<T>, with T being the type you want to use, meaning functions that use .AddListener(SomeFunc) will need to have that "T" param to add to it, regardless if thats from the inspector or by code
Thanks
Maybe you could search your project for t:font which should show you all the assets of type "Font", there is probably only 1 or 2 built-in fonts by default the engine uses, assuming you dont have TextMeshPro or any other packages/assets that may include their own fonts
Its not a project its a BepinPlugin
So I can only use included fonts
If your doing this in Unity, you can still use the Project window to find the fonts in your project, if this is entirely outside of Unity, im not sure how else you could find what your looking for, but Resources.GetBuiltinResource seems like a Editor function to me, so I imagine you have access to a project to use that API
Im coding in visual studio but I do not have the project of the game, I just want to know what the avalible fonts are, Resources.GetBuiltinResource is avalible if you use UnityEngine as a reference.
velocity.x = Mathf.MoveTowards(velocity.x, topSpeed * 60, topSpeed * 60 * acceleration * Time.fixedDeltaTime);
This is my movement code. I am wanting to be able to input a simple number for time to decide how long it takes to get to top speed. Currently in this, if I input 1 for acceleration I will arrive at top speed in 1 second, but I want to be able to say arrive at top speed in 1 second or 2 or .5 ... etc.
Anyone here know vector math? Red is the current vector, Blue is the desired vector
Proj is in 3d, if that matters
What's the relationship of blue to the other two?
If blue branched from the origin of green (the initial point) it would be an add operation - would imply you know the blue vector.
I would like blue to be parrallel to the camera, dragPos is the worldCoords of the mouse, but the distance may change depending on how far away the camera is
the circle is what is moving, i do not know the blue vector
im trying to "flatten" the red vector
So we'd need to know more about the circle else there's little binding the vectors together.
How is red related to this?
There isnt a way to use green to cancel out the forward movement of red?
i can send a gif for clarity gimme a sec
red is the current vector I am getting
can you explain in words what you're trying to do?
That is vector projection
Vector3 blueVector = Vector3.ProjectOnPlane(redVector, -greenVector);```
This^
I'm assuming this should have been how it would look:
Sure, I have a camera, and when I click, I can drag a 3d object across the screen and I want it a consistant distance away from the camera (the original distance between the two), the way I did it before was I just overwrote the z axis to be the distance between the camera and the object, but if I rotate the camera, that doesn't work
In this case, it'd just be adding the two vectors together.
though for a consistent distance from the camera you can also do:
Vector3 mousePos = Input.mousePosition;
mousePos.z = consistentDistance;
Vector3 resultWorldPosition = cam.ScreenToWorldPoint(mousePos);```
You can use namespaces, but something has to compile and execute that code, if its not Unity, how and when is that UnityEngine.Resources.GetBuiltinResource being executed?
title.font = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
title is the type of text
which is attached to a gameobject
I dont think I understand your setup, GameObjects are specific to Unity, so your code would have to exist in a Unity project, and attached to a Game Object in a scene that has this "title" text component attached to said object, for any of your code to execute, it would have to be compiled by Unity or some other system (then that system has to know how to recognize Unity-specific code and API) which means you should be able to use the Project view to search, I think you can also search in a similar way with AssetDatabase (though thats in the UnityEditor namespace), in terms of just default fonts, without Unity itself, im not sure how else you can find anything aside from guessing Arial is likely a default font
My setup is a visual studio project, using .net standard 2.0, with the unityengine dlls imported so I can use them as references (meaning I cant search in project view or anything like that)
hey guys can anyone help?
public async void TurnOffAfterTime(GameObject gameObject, float time)
{
await Task.Delay((int)(time * 1000)); // Convert time to milliseconds
// Check if the GameObject is still active before turning it off
if (gameObject != null && gameObject.activeSelf)
{
gameObject.SetActive(false);
}
}
This is an async function which i am using to set an object disabled. The issue is that when i exits the play mode and now i am in the unity editor the thread completes itself and makes the object disable despite playmode exited. How can i avoid it from executing after playmode exited?
cancellation tokens. or just use a coroutine if you aren't on 2023 to use Awaitable
dont have an idea on cancellation tokens. I guess i ll do some research and come back
coroutine doesn't go with my usecase otherwise that's my first option
how could it not. you can easily just use a yield return new WaitForSeconds
if you use a coroutine you also wouldn't have to do that check to make sure gameObject isn't null or that it is active since a coroutine started on that object would be canceled if the object is destroyed or inactive
thanks, I was getting an error while using coroutine thats why i used the async await. Turns out it was my mistake. The error was coming thought another thing that i now have fixed and the coroutine is working just fine. Thanks @somber nacelle
Ah I see, so then you may only have the documentation to go off of: https://docs.unity3d.com/560/Documentation/Manual/class-Font.html if its not covered there, im not sure where else you might be able to find that info outside of the editor, though you could probably make a new project to search for the fonts or maybe theres a Unity Technologies github project that might contain them, though the version might matter, as I think later versions may use different fonts compared to older versions (though I could be wrong)
The Unity Manual helps you learn and use the Unity engine. With the Unity engine you can create 2D and 3D games, apps and experiences.
Alright, I may be doing something wrong so I recorded a demo of my problem and pasted the code, the mousepos.z was my original solution, but moving/rotating the camera then it doesnt work as intended (first gif), just tried the plane projection but maybe i have done something wrong (second gif)
Vector3 dragPos = Input.mousePosition;
//dragPos.z = (cam.transform.position.z - grabbedObj.transform.position.z); // original z dist solution
dragPos = cam.ScreenToWorldPoint(dragPos);
Vector3 distVect = cam.transform.position - grabbedObj.transform.position;
Debug.DrawRay(grabbedObj.transform.position, distVect, Color.green);
//grabbedObj.transform.position = dragPos; // for z dist sol
grabbedObj.transform.position = Vector3.ProjectOnPlane(dragPos, -distVect);
I figured the sol in the first gif was because of using .z and the camera wasnt on the z axis anymore, but could it be something else?
The first few seconds of the first gif is what is intended, just regardless of cam pos/rot
Hi everyone !! I need some help !! I was Working on a mobile game and i implemented advertisement and it work fine , today I Implemented some post processing and to affect the UI I used the screen space - Camera on the canvas Renderer mode , then when ever I clicked the ads button it show mw this error : UnityEngine.Advertisements.Placeholder.HideSkipButton (UnityEngine.GameObject canvasGameObject) (at Library/PackageCache/com.unity.ads@4.4.2/Runtime/Advertisement/Platform/Editor/Placeholder.cs:182)
UnityEngine.Advertisements.Placeholder.Show (System.String placementId, System.Boolean allowSkip) (at Library/PackageCache/com.unity.ads@4.4.2/Runtime/Advertisement/Platform/Editor/Placeholder.cs:79)
UnityEngine.Advertisements.Platform.Editor.EditorPlatform+<>c__DisplayClass14_0.<Show>b__0 () (at Library/PackageCache/com.unity.ads@4.4.2/Runtime/Advertisement/Platform/Editor/EditorPlatform.cs:165)
UnityEngine.Advertisements.Utilities.CoroutineExecutor.Update () (at Library/PackageCache/com.unity.ads@4.4.2/Runtime/Advertisement/Utilities/CoroutineExecutor.cs:17)
and this error took me on this method : private static void HideSkipButton(GameObject canvasGameObject)
{
canvasGameObject.transform.Find("Skip").gameObject.SetActive(false);
}
On the UnityEngine.Advertisements namespace
This should work for you
I'm trying to make sense of some code from a unity app, it has tons and tons of code that look like this
How can i make two objects with same material but different colors?
Solved : The problem was under the Max Texture size on the player settings i was setting it to 1024 and when I switch it back to 2048 it worked fine
I have a static variable that is reset to its default value when accessed outside of the class it's in and I don't know why.
public static UnitDestroyData LastDestroyed { get; private set; }
public readonly struct UnitDestroyData
{
public readonly int strength;
public readonly float speed, health;
public readonly System.Type type;
private UnitDestroyData(System.Type type, int strength, float speed, float health)
{
this.strength = strength;
this.speed = speed;
this.health = health;
this.type = type;
}
public static UnitDestroyData CreateUnitDestroyData<T>(int strength, float speed, float health)
{
Debug.Log(typeof(T));
return new(typeof(T), strength, speed, health);
}
public GameObject Reanimate()
{
GameObject obj = new();
var unit = (UnitData)obj.AddComponent(
type.GetType());
unit.Strength = strength;
unit.Speed = speed;
unit.MaxHealth = health;
return obj;
}
}
It's set in an OnDestroy method:
protected virtual void OnDestroy()
{
LastDestroyed = GetDestroyedData();
Debug.Log("Destroyed");
Debug.Log(LastDestroyed.type);
}
those debug log statements are called, and it logs the correct type. Yet the very next debug log it's null, which is called from just a separate test class:
StunnerUnit bu = new GameObject().AddComponent<StunnerUnit>();
Destroy(bu);
Debug.Log(UnitData.LastDestroyed.type); // null here
In addition, the strengh, speed, and health are all 0, even if directly set otherwise.
That makes no sense to me.
actually it's only null in the start method. What!?
if it is only null in Start but you also only assign it in OnDestroy then what are you expecting to happen? ๐ค Start will obviously run before the object has been destroyed
no, on a seperate test object i have the very last code block.
but I think it's because OnDestroy doesn't immediately run.
yes that was the problem.
Does anybody know how i can "ensure you are signed in through the authentication sdk and try again"? ||context: I'm trying to setup cloudsave but i get thrown an exception stating my access token is missing, i cant provide code since no line or code is mentioned||
i did look around the docs, discord and other places and found nothing relating to the matter, and I ensured I was logged into services
When I change slider.value, the value doesn't actually change but if I debug.log(slider.value) it prints out the value I gave it
and in the inspector the 'Value' isn't different either
this may be a dumb question but you did give it a fill, correct?
no ones really gonna be able to help unless u specify what you actually did.
like i said the actual value is 0 and now im actually more confused because i exposed the variable im setting the slider to
^ /or give the code/error message
are you certain you are modifying the slider that is in the scene and not perhaps a prefab?
does start run in the prefab instance?
i mean when i check the cached slider it matches up
public byte CurrentObjectiveProgress
{
get => _currentObjectiveProgress;
set
{
_currentObjectiveProgress = value;
UpdateProgress();
}
}
private void UpdateProgress()
{
slider.value = CurrentObjectiveProgress;
Debug.Log("New progress:" + CurrentObjectiveProgress);
Debug.Log(slider.value);
}
i thought maybe it was because i was using byte but i changed it to float and that didnt change anything
no. but i'm referring to your reference stored in your slider variable. are you certain that is not a reference to a prefab
yes
if i click the reference it highlights the object i expect it to
then either something else is changing it back to whatever it was before this method you've shown runs, or you aren't showing enough actual context
in the inspector, drag the value manually and verify the slider ui actually does change as expected
i did
it changes when i change the value
did you try it during Play mode?
idk what you mean by that
yes
i dont even know what u mean by that
manually changing the value in the inspector and making sure the ui changes accordingly
๐
no need to suggest random things. literally every suggestion that can be provided right now is a guess. We need more context
also, learn to take a screenshot please
ill try just setting it to a random number between 1 and 100 then (the min and max is set to 0-100)
literally all i have in my code to update a slider is
[SerializeField] Slider metallic;
// later on in some method
metallic.value = data.metallic;
which is just a float
im setting the value too but it doesnt do anything .-.
do it on a new slider
i mean it does, somehow because if i do debug.log(slider.value) it gives the value i just gave it
again, if it isn't showing the value you expect after you see that log, that means something else is changing it
ok well they are changing if i just set them to a random number every frame
add this log to the beginning of your method
Debug.Log($"Slider {slider.name} - {slider.GetInstanceID()} current value: {slider.value}");
and this at the end of the method
Debug.Log($"Slider {slider.name} - {slider.GetInstanceID()} value {slider.value} matches {CurrentObjectiveProgress}: {Mathf.Approximately(slider.value, CurrentObjectiveProgress)}");
and show what each prints
says true every time
it's a prefab
so im changing values in an instance of a prefab?
the instance ID would be negative if it were an in-scene object
not an instance of a prefab, the prefab itself
that doesnt make sense though because if i click the cached slider it highlights the in scene object
you're likely reassigning the variable somewhere then
of course you haven't shown enough context for me to take a guess at where and all of the troubleshooting so far has really just been taking guesses at what the issue might be so ๐คทโโ๏ธ
so something else is changing it if the values are not what you expect them to be
its a mess which is why i dont really wanna post it lol
i have a feeling its a problem with CurrentObjectiveProgress
no, the issue is that some other object is assigning a value to the slider
thats not possible i dont think?
why would that not be possible?
the only location in that code you've shown where the slider's value is updated shows that it is being set correctly by this code but something else has changed its value between the time it was set and when you check it again
which is exactly why i gave you the logs to print. you can clearly see it is being set to 0 in this code, but then it is suddenly 9 from something else
Hello,
is this a position lerped to the grounded position during a step-off? A jump landing causes a screenshake rather.. but im curious of this mechanic.. i wonder how they decide when to lerp and when to act normal.. maybe checking horizontal velocity and under a threshold.. when it becomes !grounded it casts down to see how far its falling and if that is also under a threshold then lerp..
what do you guys think?
yea i showed current objective progress and it always shows as 0..
right because that is not the issue. the issue is that the slider's value is being changed from somewhere that isn't the code you've shown
the only time i ever change a sliders value is on that one line
apparently not
and as the logs prove, this code is not the problem. it's some other code that runs between when this code runs that is causing your issue
what in the logs proves that?
the fact that each time the method is called the slider's value is reset to 9
you're obviously not setting it to 9 in this code because the logs show you set it to 0 from here. so logically, the issue lies elsewhere
you can cry about how you are sure you aren't setting it somewhere else, but obviously something is affecting it that isn't the code you've shown
i think you might be getting confused by the multiple objectives
im going to set it to one objective
those logs were running once per each objective so the numbers would be pretty different
okay well i'm done attempting to help since you prefer showing literally no context
like obviously the log for the beginning of the method was to show you the value before you set it each fucking time you set it
I want to create a pathing system for a character, so whenever he hits a new tile there will be a random chance something happens. how would I do this>
distance check to your next target
A* algorithm for pathfinding since that is practically perfect for grid based pathfinding.
then you just need some way to determine when the object gets to a new tile, this can be done using physics messages/physics queries (where each tile would need its own collider), or simply checking the position against the tilemap to determine what tile it is on, distance checks, etc.
public void AddObjective()
{
if (_objectives.Count == 255)
{
Debug.Log("Skipped creation of new objective due to hard limit.");
return;
}
// TODO: Add code for adding objectives to the UI
// Instantiate
var newObjectiveNode = Object.Instantiate(objectiveUIPrefab, uitransform);
// Rename
newObjectiveNode.name = "Objective " + ((byte)_objectives.Count).ToChar();
// Get objective UI node script
// VVVVVVVVVVVVVVVVV - Used objectiveUIPrefab instead of newObjectiveNode
if (!objectiveUIPrefab.TryGetComponent<ObjectiveUINode>(out var uiScript))
{
throw new ArgumentException($"No {nameof(ObjectiveUINode)} found in instantiated prefab.");
}
some weird dictionary reference shenanigans
at least you hopefully are not on time pressure
gmtk game jam?
mhm
it sucks
im in the idk how to code advanced ai
big scope for 48 hours
maybe dont aim for advanced AI if you have never heard of A* star before
its not really advanced ai I just don't know how to do this
i just need it to go up and down and check every tile
you havent really provided context about what you're actually trying to do.
"whenever he hits a new tile there will be a random chance something happens" sounds literally like a position check to me
ok ill explain
i want a game object to walk around the brown path
and i want it to check the tiles
and 1/5 chance it;ll spawnin smth
if it makes you feel better this is all i have
in this code, does it affect physics? or does it just affect the render and not rigidbodies and colliders etc etc
im just so confused how to do this though'
if you rotate an object, its collider will also rotate.. i dont know what you mean affect physics. Setting the local rotation should wake up a rigidbody if its asleep, but i doubt thats what u meant
you're manipulating the transform, this does not use the physics engine . . .
well have u started by having an object walk around in the first place
idk how
thats the thing
and i don't know how to spawn a tile in in a tilemap through scripts
follow tutorials, and break your problem down into steps. You were asking how to create a pathing system for your character with a random chance of something happening, but you dont have a character to start with
i'd look at tutorials and start in #๐ปโcode-beginner not here . . .
yeah. i am rewriting the code rn
I have a basic script that applies impulse force on the circle based on how far the mouse is dragged after clicking. However I'm assuming as the circle comes back down the velocity grows exponentially and thus makes it feel janky since the force applied is not enough to overcome the exponentially built-up velocity. If this is the case, is there a way to make it so there's not an exponential increase in velocity due to gravity? Rather a linear fall.
I have an asset library that I like, and I copied it into a new project but left the meta files intact, and now all the fonts are broken. Is there any easy fix for this:
(should look like this:)
The TMPro font and atlas appears to be properly imported
It's not exponential, gravity is a force applied per time step, the velocity grows linearly (with no other forces).
I think your idea of trying to mess with how gravity works would make the physics very strange. Instead look at setting the velocity directly instead of applying an impulse if you want it to be snappy and independent of its current velocity
I fixed it with linear drag however i like this idea thank you
I have a simple class and part of it "escaped?" the script component
(Unity 2021.3.4f1)
Has this been fixed in a more recent unity version?
are you on a really ancient version of 2021.3? because that was fixed in like patch 7
yes
so update xD
I'm just making sure, my internet is so slow its going to take a day
2021.3.5 has it fixed
ok good
ah even sooner than i remembered then lmao
Hello! I'm making an FPS game, this means that the main camera always has to be attached to the player.
My question is if anyone knows which is the best method to keep the camera attached to the player, because I can think of the two classic ones, which is to use a script that updates the position of the main camera always in the position of the player, or the Another option is to make the main camera a child of the player object.
And I ask this because the character uses Rigidbody (physics) to move, so I don't know if there will be some kind of conflict with movement using physics and any of the camera positioning methods. (I heard somewhere that making the child camera of the player object and moving it through physics was not a very good idea because it could cause bugs from time to time, so that's where my question comes from because I don't know if what I heard is true)
they both work fine
rigidbody controls the transform
if it's parented it moves with it
ty
!manual
๐ The Unity User Manual helps you learn how to use the Unity Editor and its associated services. You can read it from start to finish, or use it as a reference https://docs.unity3d.com/Manual/index.html
or just use cinemachine to make it much easier for you . . .
void OnTriggerEnter2D(Collider other){if(nm.isStopped){//check tile}}?
bassicly have a trigger with the size of a tile
make the ai move to the middle of the tilw
when is stopped check tile
also you could check the tag aswell to make sure
just wanted to ask if this is efficient to catch user's input like this:
private void OnGUI()
{
Event evt = Event.current;
if (evt != null)
CheckEventType(evt);
}
private void CheckEventType(Event evt)
{
switch (evt.type)
{
case EventType.KeyDown:
KeyDownEvent(evt);
break;
}
}
private void KeyDownEvent(Event evt)
{
switch (evt.keyCode)
{
case KeyCode.Backspace:
BackspaceKey();
return;
case KeyCode.Delete:
return;
}
ValidateInput(evt.character);
}
is there a way to get the gameobject a raycast2d is hitting?
this is what im having right now
//Debug.Log(_hit.transform.name);
if (_hit )
{
Draw2DRay(parent.transform.position, _hit.point);
Debug.Log(_hit);
_hit.transform.gameObject : GameObject;
}
else
Draw2DRay(parent.transform.position, new Vector2(defDistanceRay, parent.transform.position.y));```
What on earth is _hit.transform.gameObject : GameObject;
idk i looked it up and thats what it said
im not the smartest guy
That is not valid C#, so I have no idea what would recommend that
how would i get the gameobject then
_hit.gameObject
Declare a variable like you would normally
oh
Is it really that simple
that's GameObject property of _hit
Also that doesn't make sense if you look on it. You have already written gameObject, haven't you?
_hit.transform.gameObject : GameObject;
yea
would something like this work?
GameObject lazerHit = _hit.gameObject;
yes
If your IDE isn't giving you error underlining and proper autocomplete you need to configure it !ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
oh please
it works on my lpatop but not my pc
I see, you should access its transform first then
thank god for this
yea that fixed
Then configure it on your laptop pc
i meant like it works on the lpatop
but yea
same thing
will go do it
thanks @gray mural
@quartz folio
if you cannot access gameObject - first access its tranform, then gameObject from transform
blabla.transform.gameObject;
a RaycastHit2D is a struct that contains information about the object detected. check the docs . . .
oh, wow. discord didn't update. i see it's all resolved now . . .
yea i got it working
everything works now
Hello, is there a way to detect when a user presses any number on the keyboard (not num pad) from 1-9 without writing a check for every single line?
normally, for 1-2 buttons i would do Input.GetKeyDown(KeyCode.Alpha1)... , but I want to make it so it's scalable between 1-9 for an inventory on screen and quick select items
I just skimmed through the autocomplete options and I found one that says Input.inputString, but upon further examination i realized that it just says "1" "2" "3"
there is no way to detect if it's actually from the numeric pad and not the top row keys
i havent written anything that similar to this, but i think keycode is enum and probably alpha0,1,2,3.... is continuous so you may use a for loop to check (if(input.getkeydown(i)), i belong to alpha0+[0,10) ), please check the value of alpha 0 1 2 3 4 first if they are discrete then no ways
or you just want an array for mapping idx0 mapped to alpha0 1 mapped to alpha1...etc
wanna see some stupid C# code made by a person who doesnt know C#?
Anyone know why there's a big jump in time during Task.Yield() here?
private async void Start()
{
await TransAsync(0);
}
public async Task TransAsync(float target)
{
float elapsed = 0;
float dur = 0.5f;
Color start = _trans.color;
Color end = new Color(0, 0, 0, target);
while (elapsed < dur)
{
float curved = M_Extensions.CosCurve(elapsed / dur);
_trans.color = Color.Lerp(start, end, curved);
Debug.Log(_trans.color + " " + elapsed/dur);
elapsed += Time.deltaTime;
await Task.Yield();
}
_trans.color = end;
}```
this is code general
#๐ปโcode-beginner
You talking to me?
yeah
Well alright then if it's such a beginner problem wanna offer an answer
idk C#, this is my totally legit 100% might just work totally wont throw 1000000 syntax errors C# code
what do you think of it (no offence intended, im just really proud of my "C#" code)
sorry if i offended you by telling you to go to #๐ปโcode-beginner i always go to beginner channels because i dont have confidence in any of my code no matter what it is
I don't know enough about tasks to fully answer this question, but im sure that .NET does something under the hood with tasks and deciding which threads they go on.
Judging from your code you probably intended on using a coroutine though
Then what are you doing in #archived-code-general if you have any questions or request of advice stick to #๐ปโcode-beginner instead of clogging up this channel
im not looking for advice -_-"
but its code related
Mm yeah coroutines are normally the go-to but for stuff like transitions I use tasks to wait until the screen is black before saving/loading/etc. Not sure what way others do it but in my last game it seemingly worked fine. There's probably an issue with Task.Yield() being delayed for a good 0.25 seconds or so while Unity does something in the background
Anyways by increasing the duration from 0.5 to 2 it made the problem basically unnoticeable, I'm in a game jam so don't have time to make things perfect
We use this in our project, probably adaptable for coroutines aswell
private IEnumerator WaitForAsyncOperationToComplete(AsyncOperation asyncOperation, Action callback = null)
{
if (asyncOperation == null)
{
callback?.Invoke();
yield break;
}
while (!asyncOperation.isDone)
{
yield return null;
}
callback?.Invoke();
}
Interesting I'll try using that thanks
Moved to [#โ๏ธโeditor-extensions](/guild/489222168727519232/channel/533353544846147585/)
Might be worth giving this a shot in #โ๏ธโeditor-extensions instead
Oh ok
โ #archived-urp messageโ I'm not sure if this counts more as shaders or urp or even code so I'll post it here also! Please do let me know where it would've been most appropriate so I can "spam" less in the future ^^
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
Any idea, why this ball is not moving with the same position like the third bone of this lamp?
It should copy the position from "X" and "Y" while "Z" remains the original of the Ball.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class COPY_LightbulbBonePosition : MonoBehaviour
{
[SerializeField] private Transform _LightbulbBone;
[SerializeField] private Transform _Pusherball;
void Update()
{
// clone the "new" coordinates into the Pusherball Object transformation:
_Pusherball.transform.position = new Vector3(_LightbulbBone.position.x, _LightbulbBone.position.y, _Pusherball.position.z);
}
}```
You dont have touse new for this, vector3 is a struct so you will get a copy of the location back by definition
Isnt this offset of the bulb on the Z axis? If so then you should not keep the z position of the pusherball but instead use the z pos of the lightbulb
simply doing _Pusherball.transform.position = _lightbulbbone.position should work
What did I wrong?
They are using a different z
recommend that you do this in LateUpdate though, as you have little control over the script execution order
Yeah fair but isn't the offset on the Z position?
Now it is even worse.
Screenshot please?
My first assumption is this is probably some weird parenting issue because the hierarchy shows the sphere as a separate object
wouldnt matter, as transform.position is world position anyway
i feel like an idiot
Yes but if the sphere itself is the child and offset, the parent is getting set correctly while the sphere is offset
Oh you mean that the parent gameobject could also have a script messing with it right?
Although im just guessing. The code cant really have an error of not copying the x and y unless something visually isnt where its parent is
Oh wait, nevermind i didnt take enough of a detailed look at the hierarchy! That could definitely be it, the pusher sphere might have a localposition set, good shout!
Its not moving at all with the position of the third bone, also my offset is now gone, thats why I only want to move X and Y while Z remains the original so I can push with it as animation later on.
This script should make the ball always move to the bones X and Y so it can always be pusshed.
Honestly on mobile this is too hard to watch.
Check if "LightBulbPusherSphere" does not have a transform value set
Yeah watching videos is awful for debugging
Looks like he has physics on it too
Remove the physics from the actual model @tight fjord
And you might have to use rigidbody.moveposition instead of directly letting the transform
Hes also using some magicsphere script or something, idk if thats a library or something
why? the transform position of bone.003 is exactly what I need for the ball.
So it always stay on top of the lamp in X & Y.
Im talking about the sphere that you aim to move
I want that sphereHolder moving always to the same position like bone.003
Honestly I dont even get what the video is supposed to show
Isnt the sphere supposed to copy the lightbulb bone, why try to move the sphere and not the lightbulb
its showing that the ball is not moving on X and Y as the same position of bone.003
This is probably some physics stuff where the position keeps getting overwritten
if the lamp is bouncing, the ball should also bounce his position X and Y, so that the ball always covers the lamp from the 2D canvas perspective.
why do you not care about the Z postion?
Again, the sphere is bouncing on the lamp aswell because they are both physics objects
So you need to to either ensure that they ignore eachother, or remove physics from one of the two
Z is used for later, thats why I want to move the HOLDER of it and not the ball itself.
I will make later a animation to move fast the "Z" axis forward/backward, to push the lamp, so it is looking if you pushed the lamp with your mouse. and I want to push the lamp even if it was already pushed, so the ball needs to move at the same X & Y like the bone.003
I'm getting the error The targets array should not be used inside OnSceneGUI or OnPreviewGUI. Use the single target property instead. and I'm not sure why
WaypointPathEditorData data;
List<Vector2> pathData = new();
private void OnEnable()
{
data = (WaypointPathEditorData)ScriptableObject.CreateInstance(typeof(WaypointPathEditorData));
}
(...)
public void OnSceneGUI()
{
Event e = Event.current;
PathEditor.DrawPath(ref pathData, e, ref data.TempPath, data.IsReplace);
}
So? This really depends on how you want to apply the force down the road
You can simply apply a force to the physics object, and it wouldn't matter what the z position is
Feels like we are encountering this right now
Asking about your attempted solution rather than your actual problem
my hope was that this tiny script should do it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class COPY_LightbulbBonePosition : MonoBehaviour
{
[SerializeField] private Transform _LightbulbBone;
[SerializeField] private Transform _Pusherball;
void Update()
{
// clone the "new" coordinates into the Pusherball Object transformation:
_Pusherball.transform.position = new Vector3(_LightbulbBone.position.x, _LightbulbBone.position.y, _Pusherball.position.z);
}
}
it should get the transform of the bone.003 and the transform of the ballholder and change the ballholders position to the same like the bone.003 so it does always cover the lamp, if to look at it in the 2D perspective, no matter how it is bouncing, cause it always moves in front of the lamp (bone.003=
This will never work because both are physics objects
You should add debugs to see if the values are what you expect, because this code will set the objects position to the other objects x y position
why is this a problem?
it shows me in the Inspector, that it have a bunch of transform data changing every frame, cause the lamp is not hanging without motion.
thats exactly what I try to do.
Where, I dont see any debugs in the code
The inspector values are local position. You wont be able to compare those by looking at it
Really you should take this copy xy code and apply it to a basic cube with no rigidbody, maybe even further away from the light. Move the light and check if the cube follows.
it should looks like this, if the lamp is moving, the X and Y of the ball should always cover the lamp from the 2D canvas perspective.
(I paused it, so I can take this "fake" screenshot, cuase it is not doing what I want)
Alright so first things first, two physiscs objects trying to move into eachtoerh will cause them to continiously bump eachother (what happens if you try to compress two balls in real life to the same position?)
Then there's also a portential problem that your current way of moving directly accesses the transform, instead of using the related physics components for that - thus resulting in it immediately being overwritten by the physics engine
And then you also make a big deal about maintaining the current Z position, which does not matter for your usecase
only complicating the problem for yourself further
not if the Z is not the same and have a bit of offset to it.
Then maybe try any of the suggestions we gave in the past 15 minutes?
Instead of repeating the same question over and over
Try this on an empty cube. I have no clue what's happening in the hierarchy of that sphere. It has a child and a random component I've never seen
I may just think that you don't quite understand a question or my goal behind it...
Read this: https://xyproblem.info/
Asking about your attempted solution rather than your actual problem
because you have supplied very little context, and are asking about an attempted solution rather than explaining your goal, what you've tried and what you are currently stuck on
Maybe try repeating it for the 10th time. Im sure saying you want to copy the x y position again will change something
The code itself is trivial. The issue is within the setup
As we've been trying to help you debug
Have you actually added a debug statement, checked if the child sphere had any offset, or tried this on a basic cube like we've suggested?
I use MagicaCloth2 for the physics of it.
My goal is it to make not only a lamp that moves by wind a tiny bit in the title screen, the Player should also be able to click with the mouse on the lamp to "push" the lamp and make them swing around.
To make this happen, I made a sphere with a magicacloth2 collider that can interact with the bones of this lamp (including the wire) But I don't just want to push the lamp if it is mostly standing still so the "pusherball" is in front of the lamp, I want to make the player even push the lamp even more, if it is already swinging, so the ball needs to swich at the same X and Y position of the bone.003 of the lamp, so that I can push with a animation the ball its Z axis to the lamp.