#archived-code-general
1 messages · Page 240 of 1
both get destroyed and the object i assigned to activate in the placement trigger script activates
I thought you wanted smth like theres a red blue and green ornament and you only want the red and green to be able to activate the trigger but the blue do nothing
ooh or maybe just to bypass all this trouble i can just activate the placement trigger with other funcionts in game such as i wake up and the object + the trigger gets activated
maybe i can provide footage to see what i mean lol
ah i'll just make the other functions activated the other placement triggers and the item
guys i have a script attached to an object. this object's child is a particle system. what the script itself does is to just copy the player's position. everything works as intended but the only issue is as i move player the particle system rotates. i tried both local and world space options on the particle system and it doesnt work. i cant figure out why its rotating it should be just copying the position.
im actually so dumb i couldve just made a script for each item
Alright, hope recursion doesnt fuck my brain
I would assume it wouldn't inherit rotation in world space. Perhaps there's some more options for constraints on the particle system, otherwise can probably just set the rotation yourself to be clamped within the script
there's also the constraint class
How could I simply make scenes have a type? Something that would tell the Player that this scene is either Peaceful or Action.
make an SO with the scene asset and any extra info relating to the scene
How can I make a script attached to the Scene?
you attach the scene to a script
Are you talking about ```C#
public Scene scene;
Yep
Actually, may need to use the GUID/Name
can't reference the scene by asset in build
Hello.
I have a Canvas with Render Mode Screen Space - Camera.
I have a UI Image in this Canvas.
How do I make this Image's sizeDelta with the same as the current size of of 1x1 block?
The block's size changes according to the current camera size
Thoughts on how to approach checking specific conditions about the player for tutorial purposes?
I have a TutorialManager script that grabs a reference to the player controller script when they load in,
think I may start coroutines for each section that checks for conditions like basic movement, using their light, opening doors, etc
I already have simple zone triggers they can enter to trigger these tutorial messages
not sure if this is helpful
but a technique i used was a universal variable handler
and with variable like 'hasUsedFlashlight'
and the bool would be set to true
and you could check whether or not the bool was true
by accessing it from another script
Makes sense yeah, I intend to track some things that way
I can reference TutorialManager from anywhere with static methods like TutorialManager.ShowBasicMovementInstructions or something similar
within that coroutine it checks if player position has changed and then hides the message
From my notes:
1. "Use [WASD] to move"
- Short delay after spawning
- Persists until player moves
2. "Hold [Shift] to run faster"
- Persists until player runs or reaches next section
3. "Press [F] to use your light"
- Door is blocked by particle field/wall
- Persists until player turns on light
Thats just the very simple beginning stuff but yeah, making sure the tutorial isnt restrictive or overly rigid making you do every single action
I noticed a small amount of players never knew you could use a light and had a bad time with our demo as a result
At the time there was no official tutorial though, it was notes on the wall you could run by, and some people did. Most players seemed drawn to them though
Hi guys, I'm new to unity and I was wondering if someone would look over my code and suggest any improvements. Much appreciated https://pastebin.com/wEeTHq1s
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
All the transform.Finds could definitely be removed. You can instead just reference the object directly
This seem like a good way to handle things?
This is a simple example that starts the scripted tutorial once the player spawns in, it waits for the local player to be defined.
The first conditional just waits for them to move and then hides the message.
private IEnumerator StartTutorialDelayed() {
// Wait for player reference
while(PlayerController.LocalPlayer == null) { yield return new WaitForSeconds(0.1f); }
localPlayer = PlayerController.LocalPlayer;
Debug.Log("Found local player: " + localPlayer.playerAttributes.displayName +
"\nStarting Tutorial");
StartCoroutine(MovementTutorial(localPlayer));
}
private IEnumerator MovementTutorial(PlayerController p) {
if(!p) yield break;
Debug.Log("Tutorial Message:" + movementTutorialMessage);
// Display hint text and record initial position
PlayerHintText.ShowHint(movementTutorialMessage);
Vector3 initialPos = p.transform.position;
// Wait for position to change
while(p && initialPos == p.transform.position) { yield return new WaitForSeconds(0.1f); }
// Hide when player meets condition
PlayerHintText.HideHint();
}
how? bc by making them public and assigning the value by dragging it to the script would be messy
Are we looking at the same code? You're literally doing the same with other gameobjects already
And anyways, you are looking it up based on the name, this is already messy. If the name changes, you suddenly have an error
I consider this the opposite of "messy"
so i should do this insead?
public GameObject soundmenu;
public GameObject generalmenu;
public GameObject templatePrefab;
public GameObject generalButtonMain;
public GameObject soundButtonMain;
etc..
you explicitly indicate which objects you want to interact with
this is perfectly normal
so like 20 lines of just that is fine?
Yea I drag in references in inspector for most things.
note that you probably want more specific types
notice how, in my screenshot, none of these things are GameObject
they're very specific component types that are on those prefabs
I have a few public GameObject fields, but they're all in dead code I need to delete anyway
There are some attributes you can use to pretty up the inspector.
how bad is my layout then bc all this is just ui and menuscreens
If all you're doing is activating and deactivating soundmenu, generalmenu, etc., then it's reasonable to use GameObject
i mean towards the end of the script im cloning prefabs and renaming stuff idk if that would need changing
If your code looks like this:
GameObject obj = Instantiate(prefab);
obj.GetComponent<Button>().DoSomething();
consider rewriting it to
Button button = Instantiate(prefab);
button.DoSomething():
by changing the field's type from GameObject to Button
If the prefab does many things, make a component!
I have a lot of components that are mostly just a way to glue other components together
i have a MenuButton component that references a text component and a button component
it does some work, like setting up a "click" sound when you click on it, too
anywhere where i can learn all those basics bc i tried doing the unity tutorials on the unity website but i think those are too basic
I don't have a good source for this kind of thing. It's just something I figured out over time.
I didn't follow a lot of tutorials myself
mostly because I had a good programming background already
ight thanks for the help
(if someone else has suggestions, that'd be very helpful!)
vertx's site has a bunch of useful little tips like that
https://unity.huh.how
you kind of have to know what to search for in some cases though
I've considered writing my own hot takes, but I'm not sure it'd be a net positive given how many places you can already get hot takes from
do it anyway even if it's only for yourself. more backups of this kind of knowledge/useful info is never really a bad thing
Might as well as long as it's not a youtube video "top 50 things you didn't know about unity"
those make me suffer
you won't believe number 12
(number 12 is switching to local mode from global mode)
"THINGS I WISH I KNEW"
i saw one of those top 5 unity tips videos recently where one of the tips was just to use print instead of Debug.Log for some reason and at least one of the others was just bad practice
Tbh I cant even think of text-based unity resources other than unity docs, unity.huh.how and catlike coding
catlike coding is good
And some random blogs
i vastly prefer well-organized written documentation to basically anything else
hey guys today we're going to make an epic first person shooter in just 3 minutes
stack exchange is usually worse than nothing
somehow
editor error due to a window you have open that uses the graph editor like shader graph or animator. you can ignore it
ok
my health bar isnt working?
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class PlayerHealth : MonoBehaviour
{
public Slider slider;
public PlayerEnemyCollisionManager collisionManager;
public TextMeshProUGUI healthText;
private String currentHealthText;
private String maxHealthText;
private void Update()
{
slider.maxValue = collisionManager.maxPlayerHealth;
UpdateHealthBar();
}
private void UpdateHealthBar()
{
float healthPercentage = (float)collisionManager.currentHealth / collisionManager.maxPlayerHealth;
slider.value = healthPercentage;
maxHealthText = collisionManager.maxPlayerHealth.ToString();
currentHealthText = collisionManager.currentHealth.ToString();
healthText.text = currentHealthText + "/" + maxHealthText;
}
}
well it's not related to that error you posted
heres the other script too
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerEnemyCollisionManager : MonoBehaviour
{
public AttackingEnemies enemyStats;
public int currentHealth;
public int maxPlayerHealth;
private void Start()
{
currentHealth = maxPlayerHealth;
}
private void OnCollisionEnter2D(Collision2D other)
{
if(other.gameObject.CompareTag("Enemy"))
{
currentHealth -= enemyStats.enemyDamage;
if(currentHealth <= 0)
{
Destroy(gameObject);
}
}
}
}
yeah sorry this is just not working and idk why
any errors? and be more specific than "not working" what isn't working
the health bar doesnt even start full and doesnt update and neither does the text
well for starters, is this component actually attached to anything in the scene?
also you should ideally use a filled image rather than a slider, it will look better
the health bar one is on the health bar slider and the collision one is on the player
have you used breakpoints or logs to determine if your code is actually running?
i assing maxPlayerHealth to 12 and it does nothing still
that doesn't answer the question i asked
oh yeah and the current health = 0
are you referencing the correct object
for example, if the PlayerHealth component is referencing the player prefab instead of the instance of the player that would certainly be wrong
you should change the variable in the inspector, if the variable is set to 0 in inspector script will think it is still 0
i love you
Thankyou bot~
both!
The docs have { 0, 3, 1, 2, 3, 0 } listed, but you'll need to do some debugging to show what corners the vertices are at for anyone to helpfully correct the indices
By logging their positions, or displaying labels at their positions
Can you view that from the back? Ie. is it renderered double-sided?
that's the only way I can understand your vertices
I would use 0, 1, 2, 0, 3, 1 if I'm correct in understanding their layout
can you not look at the other side in the scene view?
Well, we don't really allow modding discussion here, partially because it's difficult to communicate solutions when so little of the editor is available to you.
Surely the indices are changing something? Regardless, you need to understand how meshes are constructed. I have a page on triangle winding order that also describes how triangle indices works that might help
Hey guys, just a bit confused on when (or why) I should reference a component through the inspector rather than GetComponent<ComponentType>()
Are there instances where I should use one over the other?
What are the downfalls to both methods?
convenience
Are there any performance downside to assigning components through script rather than the inspector?
downfall to linking it via editor is if you edit variables / serialized values and don't handle it correctly it will unbind from the editor, while doing it via component is more explicit to the location to where this reference may be.
performance-wise, you do know the direct reference to the component if linked via editor, but if you handle getcomponent correctly such that it doesn't need to linear search through hundreds of components/gameobjects then it should be minimal
Personally I don't use GetComponent outside of setting up serialized references in Reset and dynamic use-cases.
Setup costs have always come back to haunt me, and so has placing extra requirements on the way components are set up
I getcomponent usually if it's to that specific gameobject
feels strange to link it to itself otherwise
I don't, because I rarely create components where that's a requirement. I just set those references up in Reset for convenience, but they're still serialized
If you were say working on some UI gameobject that had a Image component / Button and you had a script that interacts with it, I'd feel like that's a case where you'd just use getcomponent
unless you mean like you mostly keep a lot of that logic off those gameobjects and centralize it elsewhere
the interpolation value in lerp will automatically use 1 if given a value greater than 1 right?
Just like the button having a serialized reference to the image despite them being on the same object, I do the same
Unity's Lerp is clamped, yes. There is an Unclamped version
Whether or not it's clamped is up to the implementation
what's the unclamped one?
oh okay thanks
this might be a thing with VS Code that is not applicable to Unity but has anyone had these popups in VS Code? it happens every time I save a script and seems to be 'Restoring' the same few scripts from my project constantly. it appears in the bottom right and doesn't really get in the way, but it's just annoying and idk why it's appearing
VSCode being its typical charming self xD
are you using the Unity extension for VS ?
How can I reset values in a component in editor when I stop play? OnApplicationQuit doesn't seem to work
Values changed during play should reset automatically.
@cosmic raincinemachineVirtualCamera.GetCinemachineComponent<CinemachineTransposer>().m_FollowOffset.y doesn't seem to
Cinemachine? I think it had a setting somewhere to keep changes during play mode.🤔
Oh yeah that checkbox was checked, maybe that is why
Yep. That's why. It is so that you can get the settings you like in action and not lose them.
Is there a way to mark a scene? I am trying to mark scenes either Combat or Peaceful. How can this be done?
oh, I'm not. didn't realise there was one. let me get that and see if that resolves it
you could always just have an empty gameobject in every scene, with a script and a boolean whether it's combat or peaceful
if it tries to load a scene and can't find the script, throw an exception
also config for unity by following this guide below
!vscode
Thank you! Just letting you know it worked!
that seems to have fixed it, and now my awake, start, and update functions are no longer grayed out. thanks a lot
I'm using mouse delta in order to move my camera, but when starting the game in the editor it always moves a large amount at start sometimes bugging my script
maybe put a thing in to skip the first frame with #if UNITY_EDITOR 😜
Could be as simple as:
#if UNITY_EDITOR
if (Time.frameCount <= 0) {
return;
}
#endif``` in Update
you can change the number to something higher if you need to skip multiple frames
I did say "in Update" didn't I?
youre right
im blind
took 4 extra frames but it seems like that has fixed it
thanks!
Why is Player Duplicating? c# private void Awake() { if (instance == null) { DontDestroyOnLoad(gameObject); instance = this; } else if (instance != this) { Destroy(gameObject); } }
I have the same code on the GameManager, but that object doesn't duplicate?
Have you tried putting Debug.Log in here and seeing which code is and isn't running?
Yes
Its printing at the instance !- this*
the null part is printed at the start of the game though
Then it's being destroyed
Yes
So it's working
This is happening though
And what are those objects? What components are on them?
Those are the Player.
Just found out that I was checking printing in another Script 
The actual reality is that "instance == null" is getting called.
Is instance static?
no
Then it would be null of course
well then of course it won't work
Thanks for the help. 😄 I need to be more attentive to my code.
Hello, I am getting a weird error when making projectiles:
This is the code that runs Instantiating projectiles:
GameObject _spawnedProjectile = GameObject.Instantiate(_Combat._Projectile, origin.transform.position + new Vector3(0, 0.6f * (_charcontroller.height / 2), 0) + pos + (origin.transform.right * 0.2f), Quaternion.Euler(dir));
And this is what dir is
MainCamera.transform.forward
Using debug, it turns out dir is approx: (-0.00872, 0.00034, -0.00017, 0.99996)
However, using dir is also used for raycasts, and raycasting (And debugging raycasting while I'm at it) works fine! How can I convert so the projectiles will work correctly? Thanks
Okay, so I know what I'm doing wrong...
Unity is weird with rotations. So I guess my question is, how do I convert transform.forward directions to eulerAngle directions. I really prefer to use just one dir in my code as it is used by both the player and NPCs to shoot
Thank you so much
you can just use MainCamera.transform.rotation though
Oh, I know
So, basically, dir is used for raycasts (hitscan). And also, it is using both the player AND the NPC view. For the player, it is as described above, for NPCs:
(target.transform.position + (Vector3.down * 0.5f)) - transform.position
Essentially, i guess this is setup for Raycasts
Before, I just did use what you recommended me for both the player and NPCs... However, I wanted to combine both into one script since they work basically the same. So, when I did, this issue came up
Thank you for your help, works flawlessly!
I am trying to make a dialogue system i have a dialogue trigger on my npc.
On my dialogue box i have a dialogue manager
but it just wont trigger,
so how are your colliders and rigidbodies set up?
i have a rigidbody on my player that is dynamic as well as a box collider 2d on my npc i have a boxcollider set to is trigger, and a static rigid body
this is on my npc
So you need to add some Debugs to your Trigger script to see what is/not happening
ok wait where do i put the debug triggers?
In code
do you not know what Debug.Log is?
i do i just dont really know where i put it
can it just be put anywhere?
what code do you expect to run when a Trigger happens?
i am trying to follow along this video and understand it, and i just dont know what is wrong
answer my question
well if i understand correctly, in unity i can create elements which have the dialogue lines or icons etc, and then sends it to the dialogue manager when the player collides with the npc
that is not what I asked.
Specifically which method in your code should run when a trigger happens?
is it not public void TriggerDialogue ()
no it is not
then im missing something
where does TriggerDialogue get called from
is it private void OnTriggerEnter2D (Collider2D collision)
{
if (collision.tag == "Player")
{
TriggerDialogue();
}
}
sorry im a begginer
yes, so that is where you need to add Debug statements
but this shows you have made all of this code and not understood a single thing about it. Programming is not just about writing code you must also understand every word that you write
wait what is wrong here on line 39
That is not how you write Debug.Log statements.
If you dont know something go and look it up in the documentation
that is also not where you want the statements, it would be pointless
@knotty sun based on the Debug.Log it is triggering
show code and console
ok, so now we need to know what is triggering this if it is not the player. So add the collision tag to your debug.log
it gets triggered when the player walks onto the npc
the player is triggering it
no, it gets triggered when anything enters the trigger
how do you know it is the player if you do not show that in the debug.log?
while looking at the console the console is empty until the player walks onto the thing
but it says player because you have hardcoded "Player" not because it is the player
Debug.Log($"{collision.name} triggered {name}", collision);```
it can be maincamera if you tag it to be main camera
we need the tag in the debug
Hello
When I recompile scripts, subscriptions to buttons in the editor window fall off, well, in general, everything is reset, the objects are null
Is it possible to fix this somehow? Should I re-init?
Are you setting up references in play mode perhaps?🤔
but the console is empty until the player walks over the thing
True but clicking the message will take him to the object so he can verify - unfortunately, not us though.
irrelevant
Did you try logging this? @lofty crest
doing that now
Make sure to click the message and see which object becomes highlighted yellow
Is it the expected object?
yes the player is the object that triggers the shroudling
use .comparetag to see if there is player tag first
then check the tag of the object that "looks like player"
Is the object tagged correctly in the inspector?
show the inspector of the Player object
Without quotations
you misunderstood me, I have an editorWindow and several buttons in it, with their own handlers (made at events). When recompiling scripts, subscriptions disappear and you have to constantly close/open the window
ok it is working
Oh, I see.
There must be some callback that you can hook to that is invoked after assembly reload.
thank you so much
InitializeOnLoad attribute maybe?
I found such events, but then it’s not very clear how to correctly unsubscribe from them
Doesn't sound like a great way. Assembly reload is not just compilation. You might be executing code when the objects are not even initialized yet.@native fable
I have found calling Init from OnFocus works well for this. You just need to set up a bool so it doesn't get Init'ed more than once
protected void OnFocus()
{
if (error == null)
{
Init();
}
}
internal void Init()
{
error = new ErrorLine(this);
Initialize();
this.Show();
}
But how will this help if all objects become null and subscriptions to button events remain?
InitializeOnLoad/InitializeOnLoadMethod attributes docs literally say that they are for keeping your editor scripts initialized on domain reloads.
unsubsribe in OnDestroy
the window in this case is not destroyed, I don’t close it
but the domain reload does
hello, I am developing a multiplayer game, with NGO (I dont want to use steamworks p2p or anything low level like that), but also want some steam integration such as: being able to join steam friend lobbies via right click -> join, or being able to find friend servers via the server browser. what addons / packages do you recommend for me to use to speed things up?
but OnDestroy is not called, where else can you unsubscribe?
It's being called for me
I'd assume that whatever you subscribe to is unloaded as well. In this case, there's nothing to cause a problem.
Everything is unloaded, yes, but the window does not close, I continue to click on the buttons and nothing happens, and when I try to close the window, OnDestroy is called and null refernce is shown on those objects that were unloaded
is this IMGUI or UIToolkit ?
This is default unity EditorWindow
Editor tool
Then IMGUI. Take a look at AssemblyReloadEvents
btw I build all of my new Editor tooling using UIToolkit it is so much better than IMGUI
somehow this is correct?
like this?
public class SdkManager : OdinMenuEditorWindow
{
[SerializeField]
private SwitchSdkView switchSdkView = new SwitchSdkView();
private SwitchSdkProcessor _switchSdkProcessor;
[MenuItem("Sdk/SDKSwitcher/Window")]
private static void OpenWindow()
{
var window = GetWindow<SdkManager>();
Debug.Log("ShowWindow");
window.Show();
}
protected override void OnEnable()
{
base.OnEnable();
AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload;
AssemblyReloadEvents.afterAssemblyReload += OnAfterAssemblyReload;
}
protected override void OnDisable()
{
base.OnDisable();
AssemblyReloadEvents.beforeAssemblyReload -= OnBeforeAssemblyReload;
AssemblyReloadEvents.afterAssemblyReload -= OnAfterAssemblyReload;
}
private void OnAfterAssemblyReload() => Init();
private void OnBeforeAssemblyReload() => Dispose();
protected override void OnDestroy()
{
base.OnDestroy();
Dispose();
}
private void Init()
{
_switchSdkProcessor = new SwitchSdkProcessor();
_switchSdkProcessor.Init(switchSdkView);
}
private void Dispose() => _switchSdkProcessor.Dispose();
protected override OdinMenuTree BuildMenuTree()
{
OdinMenuTree tree = new OdinMenuTree(supportsMultiSelect: true)
{
{ "Switch", switchSdkView, SdfIconType.ToggleOn }
};
return tree;
}
}
seems sensible, yes
Is this a place I could ask about Vivox?
I'm struggling really hard to be able to start the vivox client muted x.x
Asking questions about specific libraries usually do not fit here unless they ar every commonly used. I never heard of Vivox, and I don't think you really can get an answer here
You're better off asking in their server if they have one
Vivox is an offical unity package tough
Is there a decent way to get a REPL (i.e. an interactive C# interpreter) in Unity?
I want to play with some Json.NET stuff.
it'd just be more convenient than repeatedly editing and recompiling the test code
Unity used to develop a package for this, but it's very outdated now. No idea if it still works.
https://docs.unity3d.com/Packages/com.unity.immediate-window@1.1/manual/index.html
Rider also has an immediate scripting window when you're paused on a breakpoint, but then you have to have somewhere to pause.
oh right, I think you can do that in VSCode as well
This fork has a fix for that it seems:
https://github.com/mminer/com.unity.immediate-window
I might check that out later, but this works great! Thanks!
ok - my google skills are failing me. I'm trying to create a global list (probably a scriptable object) that contains a list of ItemOptions class. Then in my Item class I want to have a list of ItemOptions but only pick specific ones from the global list - preferably in the inspector. Is that possible? I'm failing to come up with ideas...
Hey, guys, not sure where to post this? I was only hoping for some advice. I was asked if it was possible to make a desktop application in Unity, the purpose of which would be to have a button that you press to select files (in Windows explorer), and then build an asset bundle from these selected files via another button. I tried googling around but there is a big issue number one - you cant use Unity Editor commands in a build, and I'm not sure I can build asset bundles without using Unity Editor?
Any advice on if such app is even possible to make?
Edit: I do know how to normally make asset bundles in Unity. They were hoping to make an app that can do this automatically without running Unity engine for it.
Simple answer, not possible
Thank you, that's all I was looking for. 💀
hello,
im trying to get the source collider of a OnCollisionExit, since its a child i am using .GetContact(0).thisCollider
but when doing this i get an error (there are 0 contact)
i dont understand why this doesnt work, because it does with OnCollisionEnter
I suppose that there just are no contacts since the collision ended
for more clarity:
parent : script + rigidboy
childs : collider
it feels weird, why cant i know what left what ?
Not sure, I never even thought of that.
Check the answers here, might help
https://discussions.unity.com/t/u5-no-contactpoints-in-oncollisionexit/132154
Seems like checking the last contacts from OnCollisionStay could work.
I'm not sure though - it seems really hacky
yeah
ty for trying to help
whats weird is that in the docs its says it returns the collision data
https://docs.unity3d.com/ScriptReference/Collider.OnCollisionExit.html
edit: its the data of the other collider i dont want
while i'm not sure why there are no contacts, you will have to hold onto the state in oncollisionenter
can somebody pls help me im trying since an hour or so to code a basic jump n run controller with the new input system but whenever i change a random thing i the code unity says nullreferenceexcaption what does this even mean
i forgot to edit my message, i updated my code
i have each of my child using OnCollision and calling a parentOnCollisionExit with the Collision and self
this way i got the child who got entered and exited
the issue is i have to use more rigidbodies
with unirx, you can do
this.OnCollisionEnterAsObservable()
.SelectMany(entered => this.OnCollisionExitAsObservable()
.Where(exited => exited .collider == entered.collider)
.Select(_ => entered))
.Take(1)
.RepeatUntilDestroy(this)
.Subscribe(thisArgumentIsTheColliderWeEnteredWith_CalledAtTheTimeItExits => { ... });
ima be honest this code is to complex for me
tough cookie.
but there is a variable with a value assigned😭 i dont even change something in this section its like opening the door and now the window doesnt work
that's one way of many to express "i want the collidered we entered with at the time that it exits"
you can create a bunch of variables and fields to do the same thing, it will be more code, more buggy and more complex
the error is telling you otherwise, you have to show the complete stack trace
yeah i understood nothing sry
im not saying your code is bad, im just saying i dont want to copy paste some code i dont truly understand
i appreciate your effort, ill find a way, even if its buggy, learning isnt perfect when you start
its telling you in the link what to look for, if that confuses you.. then you should start with some basic courses
i did. really. but you write exactly the same code and have errors i hate it
this isn't helpful. get the stack trace and we can start with something otherwise this is wasting time lol
also this goes in the #💻┃code-beginner
sry
you will have to share the snippet with the error.
i restarted visual studio and now everything works wtf. don´t even try explaining me this i won´t understand

So I've been just simply trying to get some sort of detection that would allow enemies to see the player to work. I'm just trying to shoot a ray to the player position from the enemy and if it hits the player it will do something but I'm encountering a problem which I can't figure out why it's happening (tbh it's probably something stupid and I'm just too blind to see it). I would really appreciate any help!
Code: https://gdl.space/qusutafimu.cpp
i want to make planets on wich you can walk i got that but i dont know how to rotate the camera when walking around the planet
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GravityControll : MonoBehaviour
{
public GravityOrbit gravity;
private Rigidbody rb;
public float RotationSpeed;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
if (gravity)
{
Vector3 gravityUp = Vector3.zero;
gravityUp = (transform.position - gravity.transform.position).normalized;
Vector3 localUp = transform.up;
Quaternion targetRotation = Quaternion.FromToRotation(localUp, gravityUp) * transform.rotation;
transform.up = Vector3.Lerp(transform.up, gravityUp, RotationSpeed * Time.deltaTime);
rb.AddForce(-gravityUp * gravity.Gravity);
}
}
}
this is the code for the gravity
Hello! I am trying to update a variable named questionItem in questionManager and when im trying to see it in the inspector, it doesnt update properly, it remains the value before
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok imma modify
questionManager: https://paste.ofcode.org/zcaHB5uyArceSuxf5NaRbL
answer: https://paste.ofcode.org/vwxPAjM6RbJEdQKWi6CPtb
@somber nacelle is it good now?
now instead of making everyone dig through your code, why don't you tell us where you are trying to do this
OnValueChanged() and isCorrectToggled() in Answer
well for starters, that questionItem variable in Answer is unrelated to the one in questionManager. now explain what you mean when you say "it doesn't update properly"
it just remains like before
in what way
keep in mind that i am neither a mind reader, nor can i see your screen
im trying to update questionitem to the first item in OnPrev() in questionManager
and the second in OnNext()
i meant the children objects in questionManager
well again, i don't know what you mean by that. and also none of the code in the Answer class does anything to any child objects
nor does it do anything at all to questionManager
as you can see in the right, the elements update in the second question even though i have selected the first one. the update code uses questionItem
you need to show your Question class since that is where anything is happening. your Answer class does not touch questionManager at all
this also appears to be a mess of singletons that are going to be a bitch to untangle and debug
answer does not indeed touch questionManager, but questionManager touches answer
and yet you said your issue is within the methods inside of Answer, which do nothing at all to anything inside of questionManager
jesus this really is a gigantic mess of GameObject.Find calls, singletons, and relying on gameobject names. you're going to need to use the debugger to figure this out yourself
imma use it then
Hello friends. I just figured out how to actually use singletons properly. God I'm such an idiot. Life is good. I just needed to share. That is all, thank you all!
A ray needs a position and a direction.
You are currently using two positions
Change targetPos to "targetDir". You can calculate a direction from vector A to vector B with B - A
So I should just do pos-targetPos and use that instead?
Okay thank you I will try that out!
I can still play my game and it works fine can I just live with my life and move on?
Looking for some advice on how to structure code in C# and unity.
I'm working on a game which I want to contain a large number of items, skills & enemies, somewhere in the 100s total.
Each of the 3 categories follows the same principle design of having 1 abstract class, and then everything inheriting from those.
The problem arising from this is how to cleanly define these items/skills/enemies, as it feels like a lot of classes which may not be necessary.
The way I would approach this problem naively would just be by creating 100s of classes with constructors defining the different fields (say damage for item), and some of those having a special behavior when attacking, for which I would have a method to be executed on an attack.
Performance isn't a huge priority for me, as this would mostly be a turn based game during the times when this would matter, but I'd still be very interested in better performing solutions that offer the same features and logical encapsulation.
I'm looking for alternative approaches to this problem, whether that is defining some stuff in XML (like the basic fields they inherit), and then reading that into a Dictionary which I would use in my constructors, or something else that c# or unity allows me to do (maybe these should all be prefabs? I'm worried about the moddability of that).
What I do like about the current approach is that I would definitely be able to keep all the data & logic of any item/skill/entity in one file, which is quite nice.
Here is an example:
I have an item class
I have a weapon class which inherits from that item class, this weapon class has some custom functions.
I have a sword class which inherits from that weapon class and changes a lot of fundamental field values
I have 5 generic swords which might make slight changes to fields
I have a special sword which wants to override a base function defined in weapon to add some functionality.
Any advice would be much appreciated and sorry for the long post
I usually use ScriptableObjects with Serialized classes https://github.com/mackysoft/Unity-SerializeReferenceExtensions
Scriptable objects for the most part when it comes to defining different values, but if you want to go with a composition approach you can define most unique logic in the sword class then check at runtime how it's constructed
Alright, ty @somber tapir @latent latch, I'll look into those for a bit and see if they're a good fit. At first glance they do seem to be more 'unity' than pure classes (especially since they'd allow non-programmers to more easily modify certain fields) but I don't immediately see any fundamental differences in the way I'd use them vs what I was thinking before
I couldn't think of a way to do composition for this setup which I would be 'happy' with
they're pretty much the same as POCO except a few unity quirks
the major benefit is making many different as assets
and being able to author them in the editor I assume?
But yeah ok
you can make them through code as well but typically You create an asset with a Menu button
they're quite powerful
Oligatory vid
https://www.youtube.com/watch?v=raQ3iHhE_Kk
Scriptable Objects are an immensely powerful yet often underutilized feature of Unity. Learn how to get the most out of this versatile data structure and build more extensible systems and data patterns. In this talk, Schell Games shares specific examples of how they have used the Scriptable Object for everything from a hierarchical state machine...
It comes down to do you want to make a bunch classes for each sword, or do you prefer a single class and just component check from that. It's just that if you do want to share some functionality with all these unique weapons then you're best to keep it all together.
That's fair, and I would probably run into some issues with that because there would be a lot of overlap between custom and custom bows as well
ty will take a look
edge cases are more of a programmer error. If there's bad combinations then just dont craft them ;)
but hey, maybe you do eventually want a bow that shoots out sword beams
I meant more that like if I'd want some specific stats in some custom weapons to be randomized eg golden bows and golden swords would both get between 1 and 5 bonus dmg, this would be annoying to do without some composition, especially since the logic could be identical so it wouldn't be super great as an interface either
like an IGolden wouldn't rly work
Or well it would
but it'd be annoying to have to copy paste the exact same code every time
if you have to copy paste the same code than you are doing something wrong.
exactly
I just wouldn't make two sword classes where one shoots beams of light, and the other that does a whirlwind attack, but later on want a sword that shoots beams of light and does a whirlwind attack
That's fair
But if it's just a handful of classes then it's probably fine. I'm just speaking for expandability
Not everyone is making a looter shooter
Hey I mean it's still worth thinking about I think
But tbf I don't think it would really change my architecture fundamentally
I could add a separate skill effect or something later
So that's not a super big concern rn
I think
// attached to base prefab
abstract class Weapon : MonoBehaviour {
abstract async Task<...> Attack(Context context);
}
// attached to prefab variant
class ScimitarOfGonads : Weapon {
public float range, damage, duration;
async Task<...> Attack(Context context) {
await Attacks.Whirlwind(context, range, damage, duration);
await context.Delay(0.3f /*seconds*/);
await Attacks.Beam(context, range, damage, duration);
}
}
@oak siren
however if you are making this kind of game for PC, use Unreal, and use its Gameplay Attribute System
You see, the thing with this is you can very much do this at the Weapon class level but having a container of actions or delegates which you'd invoke. This information would be provided by the SO data, which gives it the identity it needs.
all of that indirection is zero ROI
use a prefab, it's better
i wouldn't ever program inside a scriptable object
lists of actions and delegates to invoke => a method
just write a method
As much as unreal has some cool stuff, I'd like the game to be moddable, I really like C# as a language, and I'm not a fan of blueprints 'logic'
it's all the cart before the horse
i wouldn't invent a programming language inside XML
It doesn't need to be on the SO, but on the class itself. You can simply map keys to the method which you'd populate the container with.
mapping keys to methods, populates, containers... just write the method and call it
And I also don't expect to run into performance bottlenecks
i really wouldn't overthink it
I was trying to take inspiration from the way rimworld manages this stuff
rimworld is good despite of how it's authored, not because of
lol
You still need to make a bunch of different classes, and prefabs where you can just have a general Weapon prefab to build upon.
But so fundamentally you'd more or less suggest I go with my original approach
it's upt o you: do you want the code to be written in C#, or do you want it written in XML
yes, but i am trying to illuminate that an effect is "just" a static method somewhere
fair
@oak siren Like other people said, scriptable objets using custom editors might save you a lot of trouble. If any weapon can be summed as a collection of values and pre-defined behaviors/objects that can themselves be stored as assets, then you don't need to write them manually through a constructor.
if you want to make a method reusable, i guess, you know, make it a method and call it in mulitple places
don't do any scriptable objects or editors or whatever
all of that stuff is a colossal waste of time
trust me
it takes 5s to write a constructor and it will tell you if you've made a mistake.
scriptable objects for data is fine for reusability
there's a reason we use it over plain text or json everywhere (otherwise enjoy explicitly typing out asset paths)
but again, I speak for making more than 5+ weapons
Also, you can define "default" behaviors for any field that is left unfilled. For example, if you have an "axe" scriptable object, it can be assumed that the very vast majority will share similar base traits, maybe the same attack speed, base damage, attack animation,... in which case you will only need to fill these values if you want to override the default behavior
well yes but I would be able to do that with a normal class/constructor anyway
In this case, you will only have to write one constructor per weapon category. How you define these weapon categories is up to you
It's mostly about reusability, and ease of use. There are multiple ways of achieving that result, but using scriptable objects makes editing stats, models, animations much simpler than going through constructors
can i somehow turn all these variables into the default variables from my script ?
triple button, reset
you can also right click on any value
oh no, i meant the other way arround so the default variables become the shown variables
and i think it has reset as an option
no. you can create a prefab with the script attached and use variants of it
not in one command. you can certainly just copy and paste the values in
into the .cs file
or create a preset
that's the button that looks like two bars with knobs in them
to the left of the triple dots
How would you go about detecting mouse click at a point somewhere along a dynamic 2d path?
what is a dynamic 2d path? do you mean a LineRenderer?
@civic folio Search the web for a function that gives you a distance from a point to a line segment
Just make sure to have all the coordinates in the same Space (world or screen space)
you mean a spline probably
Most spline frameworks give some kind of "GetNearestPointOnSpline" function
I thought splines are always curves
wasn't sure how to call it
I was thinking of Sebastian Lague's logic simulator and how you can click at any point to split the wires
and how the corner rounding works, a fixed distance bezier curve?
I tried reading the source code of that once but I think it was a little beyond my knowledge
pretty sure the new splines package can do Branching
These would absolutely be splines
what's the difference between a spline and an array of points
I always thought about splines like of bezier curves
GetNearestPoint would convert the spline into an array of points anyway, AFAIK
Splines allow for infinite curvature, an array of points doesn't
A spline is a curve. It might involve an array of points as part of how it's defined.
An array of points is just an array of points.
hey gang, im having an issue where when in the editor i run my menu scene, with a canvas button for "play", it all works and executes without error. but when i build it it sorta locks up on clicking the play button. the button does even change color upon clicking, but then just stays like that
i can provide more info if needed, or even the build. im just unsure what i can share that may help
start by checking the player !logs to see if there are any errors happening when you click the play button
by running the build or in the editor?
the build since that is where your issue is happening. you don't need to manually look at the player log when using the editor since exceptions and logs are printed to the console
What's a good way to have an enemy damage you, but be killed by getting jumped on? I've tried a few different methods but they all seem to have flaws, mostly due to how fast the player could be moving when they're falling on an enemy
Is there a way to prioritize something to run before unity encounters the "enter safe mode" screen? I'd like to make a junction to another folder before it opens
what problem are you having, you can do it different ways including just math or just triggers
The way I'm doing it now is that I check if the player is touching the enemy, has downward velocity, and is more than a certain height above the enemy. This doesn't work because with how fast the player is traveling, it occasionally goes below that height threshold and thus doesn't kill the enemy. If I make the threshold any lower, you'll be able to kill the enemy just by running into the side of it with a downward velocity
Basically it's not touching the enemy one frame, and by the next frame it's already below the threshold
what about just putting a trigger just on the head where its only hittable from above?
Another way i would try it is using Dot product or something like that on the head
and only make it count as kill if the hit/collision point is within that dot product
I think that could work if I also had a trigger on just the bottom part of my player, so it wouldn't trigger by running into the side of it with downward velocity
I'll try it
Show a picture of what you mean by stretching
Whenever I try to rotate an object, it doesn't go down when the angle changes, it moves depending on the angle.
I'll show the code ASAP
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hello i am currently trying my luck with multiplayer and i have come across the problem that i am trying to fill the network prefab lists of the network manager but the list just "wants" so called "Network Prefab List" as a object,
i have no clue to what this could be or why it doesnt want objects.
does anybody now something more?
ok thanks i didnt knew that channel existed
were you just guessing your way though ?
Whenever I try to rotate an object, it doesn't go down when the angle changes, it moves depending on the angle.
i hope you realize that just simply reposting the same thing with no additional details isn't going to get you an answer any faster
Here's the code: https://pastecode.io/s/apbvhyqp
You are going to have to articulate your problem a little better.
Are you having a rotation problem or a movement problem?
This code you have is doing you a disservice. If you are looking for 2d movement you should learn some better fundamentals
https://www.youtube.com/results?search_query=unity+2d+movement
The object is moving in the direction of the z rotation axis.
It's not going down despite the direction.
Yea im going to be honest, your code has a multitude of design problems ,if you continue coding your movement like this, you will continue to have unexpected behavior.
I would advise you learn some better movement methods, we would have to rewrite your whole movement logic, unless someone else wants to step up to this one lol.
holy mother of sun
why
Yandere dev apprentice
every time they've posted code they've been asked to format it correctly. they still refuse to. and they keep using these sites that don't even offer syntax highlighting so reading it is an absolute pain
I commend you for trying but really, you should use this link and watch some videos: https://www.youtube.com/results?search_query=unity+2d+movement
yea formatting does huge difference, even still this code is scary looking lol
One thing that stand out right away is that you're not using transform.rotation correctly.
dude hates brackets fr
What do you think transform.rotation is? What type is it?
the only one that might have a chance is rotation.x == 0
even still float point approx is needed prob (but yeah rotation is prob not what you think it is)
Where should I put the brackets?
You dont have to use brackets for your code to work. Its a preference thing. But when you are not using brackets you should add spacing below each portion
Why is the position changing based of the rotation?
If the rotation is 180, the game object doesn't go down.
How do I fix it?
use euler angles
How do I do that?
have you tried googling it
I just did
Honestly, this should be in #💻┃code-beginner at this point.
Are you following a tutorial or writing code randomly?
i sure hope that isnt a tutorial on the internet
at this point nothing surpise me if it were xD
I'm using tutorials, I think.
Are you not human enough to know? What kind of statement is that? Are you or are you not following a guide in some form?
Anthony kind of reminds me of hitting regenerate response on chat gpt question
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using UnityEngine.Tilemaps;
[CustomEditor( typeof( Tilemap ) )]
public class SceneMouse : Editor
{
public Vector3 MousePos;
void OnSceneGUI(SceneView sceneView)
{
// Vector3 mousePosition = Event.current.mousePosition;
// MousePos.y = sceneView.camera.pixelHeight - mousePosition.y;
// MousePos = sceneView.camera.ScreenToWorldPoint(mousePosition);
// MousePos.y = -mousePosition.y;
// Debug.Log("OnSceneGUI");
}
}
#endif```What are these?
am i using OnSceneGUI wrong?
https://docs.unity3d.com/ScriptReference/Editor.OnSceneGUI.html
yes, it does not appear to have any parameters
I have a rotating circle collider, how can I make an object copy its position exactly without rotating? I tried using a script to do this, but the object always trailed one frame behind the position of the circle collider, which messes up my collision detection
to be clear, the script set the objects position to the circle's position every fixed update
is the circle's position also changing in FixedUpdate? if not, then the issue is because you are changing the position on a different time step
It's just a physics object, so I assume yes
Is there something like "LateFixedUpdate"?
no, you could try LateUpdate though. or even Update. or a coroutine with yield return new WaitForFixedUpdate. physics updates after FixedUpdate but before WaitForFixedUpdate and Update
Doesn't seem to fix the problem
hey guys im doing a science fair project and i need help with collsions so i have this cube that learns how to navigate the course by collidng with these walls and in order to learn i run this code when it collides the ones that are facing straight at the bottom of the picture at set at 0 and the one snext to rotated one is 90 and these perfecly fine but when the cube hits the 45 degree angle on it dosent even collide with it when i debug.log i can conform without the 45 degree angle check it collides but when i add it to the if stement it dosent detect collison anymore.is it bc its a child?
or what could be wrong?
its 45 in code and inspector
don't base your logic on the eulerAngles like that. they are interpreted from the quaternion at the time you access them and may not be what you are expecting them to be because multiple sets of angles can be the same rotation
so how should i check if the y rotation is 45?
I guess what I would need is for it to be at the exact same position as the circle, after the circle's position updates but before it checks collision. Is that even possible to do?
no because that's basically the same thing
should i do localeuler angles sicne its a child?
no because that is still basically the same thing
so what should i use insted if quaternions are not angles?
accessing differently named properties that all do the same thing (interpret eulerAngles from a quaternion) is all going to lead to the same issue where the returned angle may not be what you expect. not only that but floating point imprecision is going to cause issues with equality
did you even bother reading the information in the link i shared?
yeah
see
okay well that's not even the important part since you weren't reading the individual components of a quaternion
what importance is 45 degrees specifically in your game? what are you trying to do with this cube that learns to navigate
im checking bc the way it collides i need to check when it exits if its xposition is less than hte
checkpoint postion
its really imporatnt
but it depends on the rot
and its weird
but its the way the ai learns
this feels like you're trying to recreate ML agents without actually using ML
im using ml agn\ents
thats what im using for this project
could u plz show me the fix for this solutionplz then ill look into it afterwards
i prmoise
i just need this quicly bc i need have something to show in1 hour
what specifically does that have to do with the 45 degree angle?
sorry mate, i'm not doing your homework for you 🤷♂️
basically it glitche sout a bit when going ot the next target and detetct ing walls so when its 90 or 0 i can check from the ckeckpoint if when the cube exits it checkpoint rot is 0 and if it is and exits and its z pos is larger than we know not go back wards
so for the 45
i need to check the x pos
and if the x pos is less than
the chkecpoint pos
bc for the ones with 0 rot we check if the cube is above it
and when its 45 we need to go to the x pos
or check x pos i mean
could u atleast give me another hiunt?
or something im doing wotng?
plz
@somber nacelle Do you know if there's a way to do this?
Hello! My name is Ricky, and me and a friend are making a simple horror game, in a forrest within a maze. We have been using Unity Terrain - HDRP Demo Scene (and ofcourse HDRP) and started to aid foilage like grass and bushes to our floor. They are just spread around and dont look like much but are bursting with verticies causing this monstrosty of a stats window.
I have no clue what to do and how to get this to run proparly. Can anyone point out any suggestions?
- Ricky
Occlusion culling does'nt do anything for the performance.
what you're describing is basically to gibberish to others. The rotation of an object has nothing to do with where a cube is, so it doesnt really make sense. Still got no clue what you're trying to ask tbh
this isnt a coding question, but also hdrp is gonna be bad performance. You definitely dont even need hdrp, just go urp
I think my previous question was confusing so here's a video of what I'm talking about
The box collider should stay in the same relative position the whole time but doesn't
ur parented to the wrong thing
the circle collider is rotating
if I made the box a child it would also rotate
so I have to use a script to set the position
u put it inside update ?
It's in fixed update
put it in update
I think that fixes it visually but I don't think it fixes the physics of it
if you want something more accurate ditch the script and the separate object comepletly
use physics queries inside update
BoxCast, OverlapBox or even CheckBox
I'll look into those
https://gdl.space/iqebofoyup.cs does unity have other callback that happens literally everytime? (without needing to have a TileMap selected, cause this one does need)
maybe someone in #↕️┃editor-extensions have a better answer
Unity is calling a constructor in a POCO class when I recompile. I don't believe is serialized anywhere, but removing [System.Serializable] makes the issue stop.
I'm loading something from Resources in the constructor, which is causing an error.
I'll get around this by just moving this logic to an "init" method I explicitly call, but...this is very weird!
The stack trace isn't very enlightening here.
It looks like Unity always winds up constructing an instance of a field type if the type is serializable, even if it's not serialized
a minimal working example:
POCO.cs https://gdl.space/ikiranoziv.cs
Child.cs https://gdl.space/eweyoguciw.cpp
(i originally thought inheritance was involved, hence "Child")
the more you know, I guess 🌠
it should trigger an error on recompile if Child is attached to an object in the scene
yea unity objects always create a poco class they own when it is serializable, you cant even null it
doesnt even care as well for modifiers
you can make the field [NonSerialized] though
(ʀᴇᴀʟɪᴢᴇᴅ ɪ ᴊᴜsᴛ ʀᴇᴘʜʀᴀsᴇᴅ 80% ᴏғ ᴡʜᴀᴛ ʏᴏᴜ'ᴠᴇ ᴊᴜsᴛ sᴀɪᴅ)
I doing think NonSerialized helped
Well thats the problem tho! URP gives the same results
And yes, its a different project
i just found out about StateMachineBehaviours and they seem like a really interesting way to manage behaviors that apply to specific states - now i'm thinking about trying to use them for everything (e.g. the docs use them for Grounded checks) and i'm wondering if anyone has insight on whether this is a good idea or will cause me trouble down the line?
plenty of people do it, I prefer just doing FSM by code to keep things simpler
Animator just makes all the boiler plate code for you mostly
I use state machines all the time, but not using the Animator Controller
yeah state machines seem like a clear must, but why not just use the animator controller to have a graphical representation of the state transitions then?
seems like the alternative is having two different state machines that are hopefully kept in sync
not easy to search through states
idk sometimes gui gets in the way but if thats your speed go for it
well i feel that actually, big reason why i get tired of unreal blueprints and shader graphs and wish i could just do it all by hand lol
if you work with anyone else like designers i try to make some gui tools when possible otherwise animator is a perfectly capable fsm
and you still need to write scripts , they just go inside the animator
sounds like there's no obvious pitfalls anyway and this is a prototype so i'll just give it a go
thanks for the input!
here ya go. use at own risk 😈
https://hatebin.com/dmdibmhrwl
is executealways supposed to be executeineditmode?
yea ops
prob best have that instead
this should be inside ifeditor anyway
.... but ExecuteInEditMode is just ExecuteAlways but you're too lazy to check if it works in Prefab Mode
ExecuteAlways is new ig (me is dont have it)
Things aren't "new" when you don't have them, you're just in ancient history
new is relative 
Hey guys I am trying to produce a steering wheel behaviour to control a ship but i don't know why the steering isn't giving well response is it because of transform.translate? that the ship isn't rotating
try debugging those values
its probably not what you expect them to be
okay so i tried debugging them once I move the steering in one direction and then it stops the value still goes up for the previous direction
whats that mean? which value are you referring to
Reading from world euler Y of the wheel seems a bit sketchy, I would use localEulerAngles at least
the rotationAngle in code
okay let me try that
I can't access the localeulerangle it ain't showin up in vs code
steeringWheel.localEulerAngles
Dont need the rotation in the middle
tried but didn't made any difference
I want the ship to rotate smoothly according to the steering wheel's rotation
Is the wheel's Y axis pointing forward?
yes in local
and I have made wheel a child of an empty gameobject
Also yeah log all of the floats involved in this and see if they are what they're supposed to be
Okayy
And check that rotationSpeed has the correct value in the inspector
Not just the default value kn code
yes it is set to 5
also the wheel is rotating in 360 when it is supposed to be rotate in one axis as I have locked it's constraints in rigidbody
how can I visualize a raycast for debugging? I tried using Debug.DrawLine() but its not showing in game
Enable gizmos in the game view
they're on
full script or just raycast function?
Raycast, for starters
private void checkInteractable()
{
Ray interactRay = new Ray(Hand.transform.position, Hand.transform.forward);
Debug.DrawLine(Hand.transform.position, Hand.transform.position + Hand.transform.forward);
if(Physics.Raycast(interactRay, out RaycastHit hitInfo, InteractRange))
{
if(hitInfo.collider.gameObject.TryGetComponent(out Interactable interactableObject))
{
Debug.Log("Interact ray fired and hit interactable");
InteractionTarget = interactableObject;
InteractionTarget.ShowInteractButton();
Debug.Log("Interaction available");
}
}
}```
Is this called every frame?
yes
Looks good to me then, you sure its running?
yup
it was working when i raycasted off my playercam
but its positioned at an offset, so it was detecting and printing debugs when it shouldnt have
Maybe Hand is not where you think it is?
i added a hand object and tried to raycast from it and now its liek a 10% chance it hits
try giving it long duration time
i just grab a gameobject reference via inspector
the drawline?
And maybe some color in case the scene is white or something
yea
Are you saying that it rotates wrong?
Wait why does the wheel need a rigidbody?
because I am making it for leap motion and the hands need to interact with it that's why
their InteractionBehaviour Component requires rigidbody
wdym register the hit ?
Debug lines don't collide
like my console debug lines dont show
i'm seeing the drawline hit the target, but the ray itself isnt
I meant like it should rotate in y axis but it is rotatinng in every other axis
Btw in the DrawLine you should multiply Hand.transform.forward with InteractRange for it to show the real ray
Debug.Log(hitInfo.collider.name)
ah ty
yeah, thats what i'm saying the raycast arent hitting
and i can't tell why
I need to execute a thread to do some calculations asynchronously on a lot of data in my project once, so obviously I will use the Unity Job system. I also don't know from the beginning how much data I will need to store in the end result. I'm new with jobs and I'm wondering, is it a bad idea to use linked lists to store my data and save on memory? Is a linked list of native arrays containing the data a better idea instead?
👆Do this so you get correct visuals and also check that interactrange is the right value
@long scarab
i did, its showing correctly now
Do the other objects have colliders?
which one is the colliders
yup
And the colliders are not triggers?
colliding with that red tower
they are
I can hardly tell from this screenshot
sorry , its with gizmos on, heres in game
Physics queries (raycast etc.) dont hit triggers by default
See querytriggerinteraction parameter in the raycast
Or the global Physics.queriesHitTriggers bool
Where does it say it's on by default
Not there at least
I always have to use Ignore Triggers exclusively when i use that
Ok but why are you showing me the docs
my bad replied wrong person
Ah ok
also where did you put Debug.Log collider
private void checkInteractable()
{
Ray interactRay = new Ray(Hand.transform.position, Hand.transform.forward);
Debug.DrawLine(Hand.transform.position, Hand.transform.position + Hand.transform.forward * InteractRange, Color.red, 2f);
if(Physics.Raycast(interactRay, out RaycastHit hitInfo, InteractRange))
{
if(hitInfo.collider.gameObject.TryGetComponent(out Interactable interactableObject))
{
Debug.Log(hitInfo.collider.name);
InteractionTarget = interactableObject;
InteractionTarget.ShowInteractButton();
Debug.Log("Interaction available");
}
}
}```
Idk maybe I have it on by default via script in my project
Been ages since I started a fresh project
uhhh why u put log there
should've been before If statement
if(Physics.Raycast(interactRay, out RaycastHit hitInfo, InteractRange))
{
Debug.Log(hitInfo.collider.name);
ahh to see if it hits anything at all
Hi, is there any way to change the cursor to some default OS value?
I want to have buttons and input fields that change the cursor to the operating system's default "pointed finger" and "i-beam" respectively
From what I can see you can change the cursor through Cursor.SetCursor() but is there any way to use system default specifically?
Or its hitting a child collider
omfg
it was this
it was hitting the player weapon
ah ye Osmal got it
No u
so then does a raycast stop immediately once it hits anything?
or can a single ray detect multiple objects
been doing raycast the past 7 hours 🫠
you can but I suggest you just ignore that collider
right, ill do this
ie anything player layer
just curious
there is Physics.RaycastAll
Changing cursor from OS default selection
okay so i ignored anything player related and now the ray actually hits a child object of the tower. issue now is it doesn't grab the Interactable component anymore
which is odd since it did when i cast the ray from a different object
is the child collider bigger then red zone?
that stem is the collider its hitting now
is the arm ever going to tilt up ?
otherwise you might need to make that the hitzone no? not sure how your thing works
atm it doesn't
the group i have working on it wants gravity similar to super mario galaxy, so the player kinda normalizes their position based on the surface under them
probably will add aiming up/down in the future
yea or you can do some type of autoaim for ray for now
it is hitting the stem of the tower, but when i check for an Interactable component it doesn't find it
wdym?
well is interactable component on the stem ?
meaning if you're close enough it aims from arm to the the hitzone you want
how does it know which to aim at if surrounded by hitzones?
you can use a dot product to determine which one is the most infront of you
or is there some way to always reference parent objects that carry scripts when hitting a collider?
you can do hit.collider.GetComponentInParent<MyScript>
ah perfect
@hexed pecan @rigid island tysm, finally got it working
time to just make it look pretty
How can one exclude libraries from build in a safe way? (To avoid "The type or namespace name X could not be found")
I excluded certain server-only things from client, but an android build crashes with "The type or namespace name X could not be found" exception (I don't use the components, that use the excluded libraries on the client).
In editor, everything runs just fine.
using UnityEngine;
public class SimpleFloating : MonoBehaviour
{
public static bool movePos = true;
public Vector3 posAmplitude = Vector3.one;
public Vector3 posSpeed = Vector3.one;
private Vector3 origPos;
private float startMoveOffset;
void Awake()
{
origPos = transform.position;
startMoveOffset = Random.Range(0f, 540f);
}
void Update()
{
if (movePos)
{
transform.position = origPos;
Vector3 pos;
pos.x = origPos.x + posAmplitude.x * Mathf.Sin(posSpeed.x * Time.time + startMoveOffset);
pos.y = origPos.y + posAmplitude.y * Mathf.Sin(posSpeed.y * Time.time + startMoveOffset);
pos.z = origPos.z + posAmplitude.z * Mathf.Sin(posSpeed.z * Time.time + startMoveOffset);
transform.position = pos;
}
if (!movePos)
{
origPos = transform.position;
}
}
}
So, I have this code.. i reference this script in another script and whenever i want to pause game, i put animPos = false (because i dont want to pause some animations)... But whenever i resume game by making animPos = true the gameObject position is reset... How do i stop the resetting ?
Im still stucked the wheel ain't moving properly
What is rotating it then
You didnt show anything related to that
what is the best way to pause a math function?
this sometimes the wheel rotates in a single axis and then suddenly rotates in 360 direction and the boat steering is also not happening properly
But what is rotating it? Is it just physics?
If it is a VR specific thing the I have no clue
Stop calling the function
Not sure what you mean tbh
yes it is just the physics rotating the wheel
did you read my previous post?
it's not completely vr actually
animPos, you mean movePos..?
I saw you ask earlier but I couldnt figure out what it all means
oh, I'm not actually sure but Time.time may not be affected by changing of the timescale, so try debugging that. If so, it's probably better to just make your own time variable in update
that's the only thing I can think of unless you're changing values elsewhere
yes it is
there is also Time.realtimeSinceStartup which isn't, it's real time in seconds
Thats for editor, but there is Time.unscaledTime
well, if Time.time is affected, then I guess the sin func should just continue on from where it left off so that was my guess
their question has nothing to do with timescale I think
hello, i have a button in a scroll rect and when i try to press it the onClick event is not firing. what can i do? i tried to change drag threshold of event system but it doesnt work
make sure it's a raycast target, and if you're using canvas groups that 'blocks raycast' is selected
btw when i remove scroll rect the button works
thanks, i will try it
could be blocked by another UI component and stuff like that. Alpha values will even block raycasts if there exists a UI element
yeah.. i think that it's blocked by the scroll event of the scroll rect.. idk
but when i disable scroll rect component
it works
(my button is in the 'content' parent from the viewport of scroll view)
Ah my bad got em mixed up
not too sure of the hierarchy but try setting the button* to the lowest of the UI elements
below the scroll rect, or even a child of it
crafting slot is the button
yeah, the thing is that i want to be in this location because if i will have more buttons i want to scroll between them..
i can't move it from 'content'
i made this simple sensitivity thing and it works but when i exit the game it doesnt save it how do i make it save?
Looks fine to me, as far as the hierarchy is set up. So, I could only think that something's not configured correctly.
Look into PlayerPrefs (simpler) or JSON if you'd like more extensibility
ok
If you want to use playerprefs, a high level overview of what you should do is
- when you want to change the sensitivity, save it to the playerprefs by using "PlayerPrefs.SetFloat("sensitivity", sens)"
- after the player loads into the game, to get the sensitivity from the saved setting, you use "PlayerPrefs.GetFloat("sensitivity")" and set the return value of it to the "Sensitivity" variable/property you already have
You can imagine the playerprefs as like a storage where you can store and retrieve data (in this case the value of the sensitivity)
You should just save to file (json or whatever format you want). Once you start needing to save other things, playerprefs wont suffice and will be a pain to work with.
There are many tutorials for json save systems online
This is right but if they're just making a small game with just a few settings to save, I'd go with playerprefs to get to the finished product faster.
So it depends on the scope of the game
And whether or not they're willing to learn more complex stuff
I agree with bawsi. Player pref is sort of interesting in how easy it is but because it can annoyingly fill your registry up on Windows with garbage, it's limited types and whatnot, you're better off trying to get a simple generic json or file-read/write setup. I'd give playerpref more attention if storage location was optional.. Other than that, the name implies it's for configuration - which is valid in this case (it just unfortunately floods the Windows register while at it
)
Yeah but if they don't have previous experience in IO systems then it takes more time to learn
If they anticipate a scalable system with many more settings to come, then JSON is by all means the right path to take
Right but players would higly likely not notice it if it's just a small game
it's not for editor, works in runtime too
you perhaps mistaken it with EditorApplication.timeSinceStartup
Totally agree. Just nitpicking as a developer.
That can be said about anything. I dont find it very reasonable to go for a solution just to see results quicker, when it is a worse solution.
It's the same for when people here suggest things like "cache your get component calls" or "use compare tag". At the end of the day, the user wont see a single difference, but it is better to do these things
They really ought to just let devs choose/edit the file location for Player Pref
help. still not working
photo
Do the animations on the button still play? Like when you hover over it does the color change?
should i make my player a singleton
Depends on what stuff you want to hold on it
I would make it a singleton but some people don't like the pattern so
ill try making it and see if its ok
I think it'll be fine as long as it's not overused everywhere
no
Like when you have 20+ singletons then it's a problem in the architecture of your game
if i remove mask component from scroll view the button works...
That means that either another UI element is blocking the button, or the button isn't raycastable somehow
The button is visible even with the mask right?
yeah
the buttons only works when i remove the scroll rect component from scrollview or when i remove the mask component
but i want to keep them
xd
i tried to change drag threshold of the event system
still not works
That's weird, when I use scrollrects they always work just fine with all kinds of raycastable stuff
Don't think it has anything to do with the event system
Have you tried creating another scroll rect and see if it works there? then if it does you just see the diff between the two and that could help troubleshoot the problem
okay it's a good idea
yeah.. it works if i make an empty scroll rect with button
thanks for the idea
i will try to find the differences
and solve
Perhaps you could check if the "content" property is set to anything in the old one
But great if you got it working
yeah
Hello all. I'm building a .unitypackage and it comes with a few scenes. I want to have a "Scene Switcher" where I list all my scenes and switch to them upon clicking a button. But in order to use SceneManager.LoadScene(sceneNameToLoad) the scenes should be in the Build Settings
Now, I can write an editor script to add my scenes to the build settings of whoever downloads my package but that's intrusive and I don't want to do that. Is there not another way?
I also am aware that I can use string scenePath = AssetDatabase.GetAssetPath(sceneAsset) but that only works in the editor...
Are the scenes just sample scenes showcasing the functionality of your package?
If so then common practice is just have the user load them manually by hand.
Yes they are. So, I should simply use SceneManager.LoadScene(sceneNameToLoad) in my code and instruct users to add them manually?
Well that's one possible solution, but perhaps you could just have them load the scenes manually like I said in my previous response
Without the complexity of assigning them to the build options
Ah, so your suggestion is to ditch the "menu" scene entirely?
But if the scenes need to interact with each other (like change scene at runtime) then this is the only option really
So it's like a root scene that contains buttons to other scenes?
Correct. Here's what I prepared (yet to test) - not sure how valid this is:
public class SceneSwitcher : MonoBehaviour
{
[SerializeField] private Object sceneAsset;
[SerializeField] private string sceneNameInBuild;
public void ChangeScene()
{
#if UNITY_EDITOR
if (sceneAsset == null)
{
return;
}
var scenePath = AssetDatabase.GetAssetPath(sceneAsset);
sceneNameInBuild = System.IO.Path.GetFileNameWithoutExtension(scenePath);
// Check if the scene is in the build settings
var scenes = EditorBuildSettings.scenes;
if (scenes.Any(s => s.path == scenePath))
{
SceneManager.LoadScene(sceneNameInBuild);
}
else
{
Debug.LogError("The scene " + sceneNameInBuild + " is not in the build settings.");
}
#else
if (!string.IsNullOrEmpty(sceneNameInBuild))
{
if (SceneManager.GetSceneByName(sceneNameInBuild).IsValid())
{
SceneManager.LoadScene(sceneNameInBuild);
}
else
{
Debug.LogError("The scene " + sceneNameInBuild + " cannot be found. Make sure it is added to the build settings.");
}
}
else
{
Debug.LogError("No scene name specified for the runtime build.");
}
#endif
}
}
I'll be filling in these references before releasing
If you think the users wouldn't mind having to manually add the scenes to the build options then you could do that, but I would go for simplicity and just ditch the system entirely
But you could also try the intrusive approach, so add the scenes to the list and somehow delete them after they are done using them..?
Yeah, and I guess that would look something like this:
// Fetch current list of scenes in the Build Settings
var originalScenes = EditorBuildSettings.scenes;
var newScenesList = new System.Collections.Generic.List<EditorBuildSettingsScene>(originalScenes);
// Add new scenes to the Build Settings
foreach (var scenePath in scenePathsToAdd)
{
if (!newScenesList.Exists(scene => scene.path == scenePath))
{
newScenesList.Add(new EditorBuildSettingsScene(scenePath, true));
}
}
// Apply the changes back to the Build Settings
EditorBuildSettings.scenes = newScenesList.ToArray();
I really don't like this though!
But maybe you don't even need to add the scenes to the build options
I just looked at the documentation for SceneManager.LoadScene and it seems like you can use the path directly for changing scenes
Here
And the way you could get the paths at runtime is have a config scriptableobject, and have a main handler or something for the scenes. Then when the main handler asset is loaded, you get the full paths of the sample scenes, cache them to the SO and then access the SO at runtime
Hmm, yes I see
But idk I may just be overthinking here
I think so hahah. Just didn't expect this to be an issue until I prepared the UI for the main menu scene 😆
Lol
I guess I'll simply use SceneManager.LoadScene(sceneNameToLoad); and let people manually add scenes. Thankfully there aren't that many.
Thanks for your input 👍
Yeah and be sure to include the docs to inform the players to do that, in like a readme or someting
Np sir!
hey I am rotating a steer gameobject when I interact with it but when I leave the interaction I want the steering to stop rotating so I am trying to set back to intial rotation but it isn't stop rotating
Are you using a rigidbody for rotation physics?
yes
In that case, before you set the rotation to the initial rotation, you should reset the rb's rotation velocity
this is a code related channel
i did it's not stopping the steering
Show the code
public void StopSteer() {
wheelRigidbody.velocity = intialwheelVelocity;
steeringWheel.localEulerAngles = intialWheelrotation;
// RotateShip(0);
Debug.Log("Stop Steered");
}
private void Start()
{
intialwheelVelocity = wheelRigidbody.velocity;
intialWheelrotation = steeringWheel.localEulerAngles;
}
This is the code in start
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
- If you always need it to completely stop spinning, then the variable "initialWheelVelocity" is useless and might be the cause of the issue. Replace it with a 0 instead cause that's what you want anyways.
RotateShip()?
if you are using rigidbody why not stick with rigidbody. There is rigidbody.rotation
Sorry for the bad formatting lol
But that won't stop the rotation velocity
who is talking about velocity?. He is using transform rotation when he should be using rigidbody rotation
He has another piece of code which is setting the rb's rotation velocity (probably), and this code is about stopping the rotation completely
intialWheelrotation = steeringWheel.localEulerAngles; ????????????
steeringWheel.localEulerAngles = intialWheelrotation;
what that has to do with it
That is most likely used to cache the initial rotation of the car(?) and then set the initial rotation back when the car needs to be reset
why is he using localEularAngles at all
when he is using Rigidbody component
it's like you'd modify transform.position when you have Rigidbody
non sense
But that would still work right?
no
Modifying the transform pos with rb
sure you can but why add rb then?
if you won't use it properly?
it's like having a car
but not driving it
instead you push it with your arms all the way
will that work? yes
is that correct? no
Well, one scenario I can think of is when you need a kinematic rb (a damageable for example) in order to register bullets which don't have rb
But then again bullets should be the ones with rb so idk
see I am setting the velocity to zero but the steering ain't stopping
basically you should never mix transform manipulation and rigidbody manipulation, use one or the other
that doesnt have to do anything with the issue
Yupp, just my 2 cents to ^
you dont stop it
you just reset the localEulerAngles
the velocity is not resetted
I wanted to rotate the ship as well according to the steering and that's why used eulerangles ig coz i thought that's how it's done
okay lemme try
then make sure you are not overriding it anywhere else
because that is probably the case
you set it to zero, then you set it to some value somewhere else
Can a cursor sprite colour be changed via code? Or do you have to swap out different sprites?
i dont think so as you are referencing the actual texture2d, not the sprite