#archived-code-general
1 messages Β· Page 95 of 1
no need to try and idk i guess sound so condescending. Im just confused as the unity docs for log files has no mention of the word build, built or builds
lemme see about the debuggin
||%USERPROFILE%\AppData\LocalLow\CompanyName\ProductName\Player.log||
not gonna question why that page says nothing about those logs being created for builds then
yeah just looked, the title menu is supposed to appear
and the loading menu is supposed to dissapear
which it does
the Player is the build
oh ok, i guess that makes sense
still a bit weird they dont specifically say that it applies to built projects
There's the Editor, the Player and Unity Hub logs.
it does though because the Player is the built project
that's like saying "Editor logs" doesn't specify that its for my project
All three and their specific locations were present in the above link.
Simply vocabulary, you'll get used to it.
if you dont like the wording on the page, there is a link at the bottom of the page you can click to whinge about it
Hey all!
How could I add an offset to a spawned object (projectile in this case) in it's local X axis so that I can make something like the paint draw?
I have the offsets all figured out, but when I'm trying to Instantiate, then add +- offset to the projectile local X, it just doesn't work as in the drawing.
I'm passing a "Firing Point" Transform that is a child of the player.
Firing a single projectile works fine as it's just:
Instantiate(prefab, spawnPoint.position, spawnPoint.rotation);
PD: the projectiles spawn in the world without a parent.
Hi everyone I have a, what is to me, very odd issue.
Inside the unity editor i have an object which i move along the z axis, I then have a chain of 2 hinge joints on either side of another object to make it swing like paper when the target anchor of the top hinge joint is moved. I then get the anchor point to mirror the movement of the object.
In the first image attatched you can see the object which swings (the paper) and the object which moves (the holder on top). These work perfectly as intended in the editor.
And heres the hierarchy for them along with the script that moves the target anchors to mirror the position of the holder. https://hatebin.com/mjwfqjfjnn
all of this works as intended in the editor and there are no errors. When built the top target holder moves as expected, however the target with its hinge joint does not move at all. There are no errors in player.log
to add onto this i tried changing the code to update instead of fixed update but nothing changed
Use playerprefs with a shader graph might help solve the issue π
uhm sorry i dont really get what you mean? how would i apply that here?
You can't, I'm not sure how these two suggestions are relevant to your issue
If you add a float to the shader with the hinge joint, then add player prefs it should work π
oh ok.. do you have any idea how id solve my issue then? Sorry im kinda new to this
This is word salad.
Yeah no shaders here lol
do any of you know how id fix my issue?
Nope sorry, issues like this where something works on one side but not on the other are the hardest to debug
yea im really confused by it, i couldve sworn this worked on my college computer when built so ima try that tomorrow. If that works then im at a complete loss.
My unity completely broke today somhow and i had to reinstall unity and visual studio so maybe its somhow linked to that? Idk im unsure
You can try a full restart yeah, sometimes it's good to free up some RAM especially with Unity that'll get really slow after a couple of hours
some tips to make my player stick to a sphere and rotate togheter while iam attached
make it a child of the sphere
everytime when you collide with a object?
could also do something with hinge joints to pull it towards the sphere
Also try renaming your script variables, maybe Unity picks up a change (or doesn't) which causes it to not be included in your build
You'll have to drag-drop references again into the Inspector
Just parent it.
and then on collision exit, deparent?
If it works it works
ill try a restart and see if it makes a difference, annoyingly none of my friends are on atm so i cant get them to try building it
@bronze crystalYou're probably going to have issues parenting rigidbodies to other rigidbodies
just a warning
ofcourse
I think joints are meant for this stuff.
you can imagine its more like a 3d player standing on a small planet
and this planet rotates
thats basically what i need
When should i use fixed update or regular update
unity answer: anything that isn't physics related generally goes into update.
proper answer: all game logic should run at a fixed interval. visuals are interpolated between fixed steps in the update loop.
you'll probably want the unity answer if you're just starting out
@bronze crystalRemember that you'll also need to override gravity so that it's sucking towards the planet's center
if the planet isn't on 0,0,0 origin
also if you're trying to do a planetary-scale game, you're going to run into issues extremely quickly.
Solved it with this:
// Get the local right direction of the bullet
Vector3 localRight = bullet.transform.right;
// Apply the local offset in the local X-axis direction of the bullet
bullet.transform.position += localRight * currentLinePosition;
didnt make a difference :(( this is such a dumb issue lol
i'd slap together a new (equivalent) joint and see if that also breaks in the build
yea ill see if it builds on my college computer tomorrow, if not ill try making something similar in a diff project
I don't feel like the proper answer is an answer itself lmao
So that means if I'm controlling a player, i should use fixed?
If you're new to unity, and you want to control a character controller, you use update()
If you're accessing the physics engine, you use fixedupdate
The character controller does not use the internal physics system. It simply depenetrates itself out of collisions.
Could you use the physics engine API in update()? Probably. But the engine only ticks n times per second, so it really wouldn't make sense.
Physics engine entails what
depends on the game
and, in fact the nature of the "player" in question
Oh i didn't know you could customize them via script
So i had questions about this earlier and the person i talked to recommended a minimum spanning tree to path to the different rooms in the dungeon im making. I did that as shown in the first image but as you can probably also see its not pathing to all the rooms. The start and target points are unwalkable but i added something for that in the pathfinder. heres the part of the code that runs the pathfinder and generates hallways (https://paste.ofcode.org/3ZSDHyHZk73wHtAzUXAcSq)
these pictures are not clear
what are the blue and green lines?
The first one is the dungon itself the green lines are the minimum spanning tree the blue are the hallways that were pathed. The shapes are the rooms the green square in the shapes are the doors. The second image is the walkable and unwalkable points the pathfinder uses (red being unwalkable)
ok absolutely did not notice the 1 pixel colors inside the circles
The minimum spanning tree seems correct (although you seem to have drawn it offset from the map)
The rest of it would come down to how your "pathfinder" works and the spanning tree is definitely only creating paths between rooms it is not going to do anything with regard to the specific door locations or internal pathing of the rooms, etc..
this should be easyer to see mabey
I added some code that calculates the closest door to the room its trying to path to (lines 44 - 64 in the code link)
I'm trying to add unique characters to a dictionary in a Manager Singleton script and it successfully adds them, but when I want to remove them, it's always a 50/50 on which get removed or if any successfully remove. I get errors telling me the Faction of the character (which serves as the key) does not exist in the dictionary.
Would anyone be able to tell me what's happening in this situation and how I could go about fixing it?
I just cant get it to path to all the rooms
share the rest of the code. !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.
Sure thing, here's the part of my EntityManager I'm using to add characters to the dictionary
{
if(character == null)
{
Debug.LogError("Character is null");
return;
}
if(character.FactionName == null)
{
Debug.LogError("Faction Name is null");
return;
}
if(character.ID == null)
{
Debug.LogError("ID is null");
GenerateID(character);
return;
}
if (!UniqueCharacterDictionary.ContainsKey(character.FactionName))
{
UniqueCharacterDictionary.Add(character.FactionName, new Dictionary<string, Character>());
Debug.Log("Faction Name: " + character.FactionName + " added to dictionary");
}
UniqueCharacterDictionary[character.FactionName].Add(character.ID, character);
Debug.Log("Character Added! " + character.ID + " Name: " + UniqueCharacterDictionary[character.FactionName][character.ID].name + " Faction: " + UniqueCharacterDictionary[character.FactionName][character.ID].FactionName);
int characterAmount = 0;
foreach (Dictionary<string, Character> faction in UniqueCharacterDictionary.Values)
{
foreach (Character c in faction.Values)
{
characterAmount++;
}
}
Debug.Log("Character Dictionary Count: " + characterAmount);
Debug.Log("Factions registered in Dictionary Count: " + UniqueCharacterDictionary.Keys.Count);
// Debug.Log("Faction Name Keys: ");
// foreach(var pair in UniqueCharacterDictionary)
// {
// Debug.Log(pair.Key);
// }
} ```
And here's my code to remove from the EntityManager Singleton:
```public void RemoveCharacterFromDictionary(Character character)
{
if (!UniqueCharacterDictionary.ContainsKey(character.FactionName))
{
Debug.LogError("Faction with name: " + character.FactionName + " does not exist in the dictionary");
return;
}
if (!UniqueCharacterDictionary[character.FactionName].ContainsKey(character.ID))
{
Debug.LogError("Character with ID: " + character.ID + " does not exist in the dictionary");
return;
}
UniqueCharacterDictionary[character.FactionName].Remove(character.ID);
Debug.Log("Character Removed! " + character.ID + " Faction: " + character.FactionName);
} ```
I got a lot of if statement checks and Debug.Log lines, but the actual lines to add and remove should hopefully be readable ^^
is it possible for a character's faction to change?
Yes, their faction could change like whether they were part of an enemy faction or allied faction
when the faction changes are you changing their registration in this dictionary?
if not - that could lead to the error
I will in a future implementation (thanks for the advice! π ), but in this situation, I'm just spawning them in, adding them, and when the game is active, I hit the play button again to stop and on their OnDestroy calls, I remove them from the dictionary before destroying them. No change to any of their information after they've been added to the dictionary
{
if(!isPoolable) EntityManager.Instance.RemoveCharacterFromDictionary(this);
Debug.Log(Name + " was " + "Destroyed" + " " + ID);
Destroy(this.gameObject);
}```
also nopticing your Awake on OnDestroy are virtual...
are you overriding those somewhere?
Might want to make sure you're calling base.Awake() in that case.
Maybe you never registered in Awake because you didn't call base.Awake in an override.
I called base.Awake() in my player and npc classes after initializing their data so that shouldn't be the cause--hmmm
Character.cs's Awake Method:
{
ResizableCapsuleColliderUtility = GetComponent<ResizableCapsuleColliderUtility>();
Rigidbody = GetComponent<Rigidbody>();
Rigidbody.useGravity = false;
Rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
Timer = GetComponent<Timer>();
if(!isPoolable) EntityManager.Instance.AddCharacterToDictionary(this);
} ```
NPC.cs's Awake Method that overrides Character.cs's Awake:
```protected override void Awake()
{
this.Animator = GetComponent<Animator>();
this.NavmeshAgent = GetComponent<NavMeshAgent>();
this.NPCAnimationData.Initialize();
this.Name = this.NPCData.Name ?? "NPC";
this.ID = this.NPCData.ID;
this.FactionName = this.NPCData.FactionName;
this.NPCMovementStateMachine = new NPCMovementStateMachine(this);
base.Awake();
}```
you sure you don't have any exceptions being thrown from here or something?
Not that I can see from the console:
Is there a scene load happening or something? How do we know the dictionary is the same dictionary?
Scene load? I only have 1 scene that I've been working on so far
I only have one instance of my Entity Manager running and the Singleton<T> class it's inheriting has a case in its Awake method that Destroys any preexisting instances so hopefully it's pointing to the correct Instance's dictionary
anyone got any ideas on why im having issues with this if you need the whole script and not just the snippets ive added tell me
Is there a component that's different from a collider that can detect if something is touching or in it? I ask because I also need a collider for detecting... well... collisions. I can't conceptually understand how to distinguish between two colliders when you can't name them or tag them differently.
collider triggers
built into the standard collider
You can name and tag them differently
Put them on separate child objects
Sorry, didn't read the entire question. Another solution would be to use collider instance IDs as dictionary keys if you want a direct lookup to something.
You actually probably want to have the collider itself as the key
Ty
I'm trying to make a script for picking up an object (but all it does is make the flashlight disappear from the game), and when I press E, nothing happens. I'm assuming it's cause of how I'm referencing the object I'm trying to pick up. What would you guys suggest?
public class Pickup : MonoBehaviour
{
GameObject PickupObject;
public bool pickedup;
public float maxDistance = 2;
public float speed = 1;
public enum axis { X = 0, Y = 1, Z = 2 }
public string keyToPress = "e";
public CrosshairCanvas crosshairScript;
private AudioSource sound;
private float r;
private bool pickingup;
private Ray ray;
private RaycastHit hit;
private bool crosshairChange;
void Start()
{
r = 0;
sound = GetComponent<AudioSource>();
}
void Update()
{
ray = Camera.main.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
r += Time.deltaTime * speed;
if (Physics.Raycast(ray, out hit, maxDistance) && hit.transform == this.transform) {
if (Input.GetKeyDown(keyToPress) && pickedup == false) {
this.PickupObject.SetActive(false);
r = 0;
if (sound.clip != null) {
sound.Play();
}
}
if (crosshairScript != null) {
if (crosshairChange == false) {
crosshairChange = true;
crosshairScript.interactable = true;
}
}
}
}
}
hit.transform == this.transform why ?
I think the script goes on the object to be picked up
guys do you know how to make a shotgun in unity
ah that's different
Very unclear what PickupObject is though
That's a really vague question
is it better to use multiple raycasts or something else?
yea why not
Depends how you want the shotgun to work
You could use Raycasts, projectiles
Whatever you want
huh ok thanks
I'm having some issues which are half code half not. I'm just using a simple script to move a UI image from off screen onto the screen. The code is in here:
https://paste.ofcode.org/BH5WQTj3WYNJpJQsfjvypD
As you can see, my problem is two things: The image/object moves into a different position depending on the resolution. The objects are anchored to the bottom of the screen. I accidentally programmed my game in 800x600 or whatever it was resolution in the Canvas, however I've set the camera and project settings to use fullscreen resolutions which would be 1920x1080 as default so I'm a bit stumped on this. Another issue, a bit harder to see, is that the images are glitching out and changing sizes as they move upwards. I'm not sure what's causing that. Could I get some help?
Id like to programatically toggle "use reference" for the left hand and right hand turn actions, but can't figure out how to do this by script. any help please?
is there a way to reference a scene in a script? I tried SceneAsset and Scene from the SceneManagement, but both cannot be set via the drag and drop parameters.
nvm. Its scene asset it seems. The drag and drop just doesnt work... need to select it from a list.
reference this script
I was trying "ContinousTurnProvider.leftHandTurnAction" but couldn't figure out how to enable disable it from there
if worst comes to worse, i could just dereference the entire action, but I was looking for a cleaner answer
show full script
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.XR.Interaction.Toolkit;
using UnityEngine.SceneManagement;
public class Controls : MonoBehaviour
{
private static Controls _instance;
public static Controls Instance { get { return _instance; } }
[SerializeField] private ActionBasedSnapTurnProvider SnapTurnProvider;
[SerializeField] private ActionBasedContinuousTurnProvider ContinuousTurnProvider;
[SerializeField] private ActionBasedContinuousMoveProvider ContinuousMoveProvider;
[SerializeField] private GameObject RightRayInteractorObject, LeftRayInteractorObject;
private GameObject RayInteractObject;
[SerializeField] private InputActionReference m_RightSettingsAction, m_LeftSettingsAction;
private InputActionReference m_SettingsAction;
public bool LeftHandedModeEnable = false;
private bool RayInteractorEnableState = false;
private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(this.gameObject);
}
_instance = this;
SnapTurnProvider.enabled = false;
}
private void FixedUpdate()
{
m_SettingsAction.action.performed += SettingsButtonPressed;
}
public void LeftHandModeEnabled()
{
RayInteractObject = LeftRayInteractorObject;
m_SettingsAction = m_LeftSettingsAction;
SnapTurnProvider.leftHandSnapTurnAction.// what goes here?
}
public void RightHandModeEnabled()
{
RayInteractObject = RightRayInteractorObject;
m_SettingsAction = m_RightSettingsAction;
}
public void SettingsButtonPressed(InputAction.CallbackContext obj)
{
RayInteractorEnableState = !RayInteractorEnableState;
RayInteractObject.SetActive(RayInteractorEnableState);
}
}
what about the other one ?
what do you mean?
the one you want to access?
... Im not sure what im trying to access, i guess thats the question
ok so what do you need to do ?
i want to toggle the "use reference" button by script
it works perfectly via the inspector window
but not sure how to via script
I'm not a unity beginner, i just dont have experience with the new input system
this "use reference" button pops up in inspector when Serializing any "InputActionReference"
OK... I have something weird. There is SceneAsset (which allows drag and drop/selection of a scene) and I have Scene, but Scene supports the SceneManager, which is used to get active scene. Anybody know how you can get Scene to become drag and droppable?
that's a checkbox
okay, a boolean toggle. sorry i wasn't using the correct nomenclature
ok so this boolean is in that script
or maybe in a struct or something, no clue. I haven't seen the script.
I don't use XR
what are you trying to do?
hella dirty but you might be able to use Object
I am trying to make the scene for my BattleManager changeable.
So when you add it as a component, you can change the combat scene via parameters.
it is not a part of the XR toolkit. it is a part of Unity.InputSystem. When you serialize the struct "InputActionSystem" in the inspector, it shows up.
I could make it via Scene name... because it seems that sceneAsset and Scene are not completely implemented in the logic of unity.
yea , ask yourself if this is worth the troubles
not even the loadscene function takes a scene object or scene asset object. Its weird
hm, I will probably just use the scene name. To save me the hassle π
that's prob smarter
are you trying to share Continious Turn Provider script ?
its just weird. You expect scenes to be optimized for switching between them. Especially with object implementation and such. Oh well.
no. this has nothing to do with the ContinousTurnProvider script nor anything to do with xr toolkit. This question is solely about the Input System. I did not see the channel here about he input System, so I moved my question there
do you happen to know about that struct?
never seen it
ok
how do i change the angle of raycasts?
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html the direction parameter
multiply an angle by transform.forward?
Finally, my combat system works π easily able to enter battle and exit while retaining the scene you were prior in. Even with the possibility to set a new scene for after combat.
float angle = 25f;
Vector3 direction = Quaternion.Euler(0, angle, 0) * transform.forward;
RaycastHit hit;
if (Physics.Raycast(transform.position, direction, out hit))
{
}```
atleast the entering and exiting the battle works xD
thanks
how would I make a point system so that when my ball touches a line then i get points
and then display the points on the top right screen?
dont crosspost
also this belongs where it was in #π»βcode-beginner
Hi guys, yesterday I downloaded Vector Graphics bcs I want to work with .svg assets. Problem is that I am building WebGL version. When I build it manually .svg works, but when I am build it via command line for some reason .svg stop working π I am using 2021+ version, latest version on Vector Graphics, WebGL 2 only. Any idea where can be problem?
hey there i am not the best at math but how whould i put i distance field in this code i cant really seem to find a soloution. The image kinda explains what i am trying to do
t += Time.deltaTime;
if (target != null && t <= 1)
transform.position = Vector3.Lerp(transform.position, new Vector3(target.position.x - distance,
transform.position.y, target.position.z - distance), t);
Usually movement goes like this: Vector3.Lerp(startingPoint, endingPoint, time); or Vector3.Lerp(startingPoint, startingPoint + direction, time);. In your code - distance seems to be unnecessary.
if i have a bunch of colliders in a rig whats the best way to receive collision events from them
im thinking of placing a script that triggers a public event in the playerscript in every rig with a collider but would that cause performance issues
yes but i would like a distance to the spehere
like in the photo
I don't think that should cause any performance issues unless you have an insane amount of objects
not sure if this is what you are asking about but Vector3.Distance() exists
i would like some sort of an offset
but what i am doing now makes it stuck at the left corner
if you like on the photo i would like it to move towards the capsule but stop before it goes into it
ok
so, you'd like to lerp towards an object and then stop before colliding with it?
if yes, are you sure that lerping is what you want here?
can said objects move or are they static?
ok, lerping should suit your needs then ig
for lerping the position you need 2 Vector3.
Your first Vector3 should be = cube's transform.position
Second one should be target's transform.position with + offset that you would like to apply
Then just lerp between the two said vectors using Vector3.Lerp()
sk the code you sent above has 2 issues that I can see, first, you need to store the starting position before the while loop, you can't use the updated value
2nd, you shouldn't do - distance, if the distance was (-3, 5, 8) it would do +3, -5, -8
What you want to do is + that distance instead
the photo hasnt really anything to do with the code
it was just to show how i whould want it the numbers there really doesnt matter
[SerializeField] private Transform target;
[SerializeField] private float t = 0;
[SerializeField] private float offset = 1;
private void Update()
{
t += Time.deltaTime;
if (target != null && t <= 1)
transform.position = Vector3.Lerp(transform.position, new Vector3(target.position.x + offset,
transform.position.y, target.position.z + offset), t);
}
this is the full code
it makes it go to a specific place
well if you want numbers that way you should probably do what I just recommended, other approaches are sure possible but I might not be able to help with some
you need to store a starting position before lerpjng
although, I would highly recommend using a coroutine for this, not entirely sure how you'll achieve this in Update
this is example code
in the player script i use a coroutine
how whould i get that point
so why not send that code instead, what you sent should work from what I can tell
right now i get the same point every time
look at the video
the cube goes the same place every time
it should go where the dots are on the new photo
that means your target position is not updating
what
no
i said it was static
The player should move towards the target and stop in front of it
how whould i make it do that
so, you have a single target with multiple distances?
well exactly like you did
could you please send the actual code this time so that we can try and figure out what's wrong
i send it right here
thats the cude for the cube and the capsule
you said that's an example code
the black sphere is where the cube is gonna move
and that you are using a coroutine
the cube and the sphere is a part of the example
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class MoveTowards : MonoBehaviour
{
[SerializeField] private Transform target;
[SerializeField] private float t = 0;
[SerializeField] private float offset = 1;
private Vector3 startingPos;
private void Start()
{
startingPos = transform.position;
}
private void OnDrawGizmos()
{
Gizmos.color = Color.black;
Gizmos.DrawSphere(new Vector3(target.position.x + offset,
transform.position.y, target.position.z + offset), .6f);
}
private void Update()
{
if (Keyboard.current.spaceKey.wasPressedThisFrame)
{
startingPos = transform.position;
t = 0;
}
t += Time.deltaTime;
if (target != null && t <= 1)
transform.position = Vector3.Lerp(startingPos, new Vector3(target.position.x + offset,
transform.position.y, target.position.z + offset), t);
}
}
well I already told you why this wouldn't work
ok this one is different, let me take a look
yes i changed it a bit while we talked
but as you can see here the gizmo does not move in front of the cube it just stands
sorry, had to go off, will take a look now
i Want my player, little sphere to stick on the bigger sphere anywhere and move if the bigger sphere would move towards adirection. someone can help with that? ```private void FixedUpdate()
{
if (isSticking)
{
playerRigidbody.transform.position = gameObject.transform.position;
Debug.Log("sticky sticky");
}
else
{
// Enable the player's rigidbody gravity
playerRigidbody.useGravity = true;
}
}```
do you understand what im trying to do?
im no the best explainer
Good morning.
Let's say I have a class A. And I have a scriptable object that was a list of class A. I will inherit this class A on to another classes.
In another class, how could I, from that list of class A, pass a parameter that would be the type of the classes that I inherit from, so that I can use methods from that class?
I don't know if I'm making myself clear or if it's possible :')
I mean I am looking at the code and I don't see a reason for it not working, would you mind explaining your goal and what's happening again?
okay
this is what i want
for the cube to move towards the target with an offset (the dot)
how whould i do that
ok, and what's happening?
this is the code right now for the dot
private void OnDrawGizmos()
{
Gizmos.color = Color.black;
Gizmos.DrawSphere(new Vector3(target.position.x, transform.position.y, target.position.z), .6f);
}
by using the Vector3.Lerp() between the starting and a target pos + offset
it just apeers inside the target
because that is what you are doing
that doesnt but the sphere infront of the player
yes
thats why im asking how whould
i
add an offset
and the sphere is at the path of the player
so, the problem is that you want to add an offset so that it's offset towards a player for the same distance no.matter which side the player is on?
yes the offset should be at same distance
something like this
so you need to move it towards the player if I understand that correctly
no the player should move to the sphere / dot's position
but i cant figure out how to get the right position of the dot
exactly what I was asking, you need to offset the dot towards a player
I am looking for the right way to do Click and Drag a Physics Object over a Floor with Walls on it. This is my setup right now. The problem is that if I drag my mouse trough the wall the Physics object will be dragged trough the wall too. But it should stop there as it should not be able to pass trough the wall.
This is a screen recording of it. And a screenshot of my visual script.
ok, you need a Vector3.Distance(startingPos, targetPos).normal * distance
how whould that look
like where whould i put the result of vector3.distance
a normal is basically the normal of that distance which is how you get where the player is lets say rotation wise looking from the target, then you multiply that by the offset from the target(you called it distance) and that should do it
exactly how I wrote it:
Gizmos.DrawSphere(targetPosition + V3.Distance(startingPos, targetPos).normal * distance, .6f);
just use your var names and Vector3 instead of V3
gtg, be back a bit later, if you have any questions feel free to @ me and I'll reply as soon as possible
@cursive moth sorry
but
float distance = Vector3.Distance(startingPos, target.position) * offset;
Gizmos.DrawSphere(new Vector3(target.position.x + distance, transform.position.y, target.position.z + distance), .6f);
am i doing something wrong?
yes, that's nothing like the code I sent above
Vector3 drawPosition = target.position + Vector3.Distance(target.position, startingPos).normal * offset;
Gizmos.DrawSphere(drawPosition, .6f);
it returns a float
you cant normalize a float
i dont thimk
think
oh, I am.dumb nvm
he needs vsctor3.Normal() instead iirc, I've had an hour of sleep and this was my fault
Did you mean (target.position - stattingPos).normalized or something?
yeah thag would work ig
I didnt see what this is for though, lemme read
yeah that's what he needed I messed up
how whould i do that
i cant normalize a float
do what osmal said, get the - of the 2 vectors and normalize it
by normalize it I mean get a .normalized property
like this?```
Vector3 drawPosition = target.position + (target.position - startingPos).normalized * offset;
Gizmos.DrawSphere(drawPosition, .6f);
yeah, I think that should work
yeah it does thanks
If I want to send an enum value from one script to another is this the best way to do that?
I want the secondary script to receive the enum value and then execute some logic upon receiving the CharacterState enum value
Also should I be checking for the switch in Update() or is there some better way of doing this?
https://cdn.discordapp.com/attachments/497874004401586176/1103246450978201691/image.png
let me just confirm
yeah it does work thanks
passing an enum should be just fine, doing a switch in Update() shouldn't cause any performance issues but if you pile them up it will so be careful
@cursive moth I just figured there might be an easier way apart from creating a method which accepts the enum, are there any other ways or am I just being stupid?
there are many ways you could do it, not neccessarly better tho
ty sexy
How can I reimport whole project?
Right click the project browser and Reimport All
Or delete your Library folder and relaunch
I have this script :
public class CameraFacingBillboard : MonoBehaviour
{
private Camera _camera;
private void Awake()
{
_camera = Camera.main;
}
private void LateUpdate()
{
var cameraRotation = _camera.transform.rotation;
transform.LookAt(transform.position + cameraRotation * Vector3.forward,cameraRotation * Vector3.up);
}
}
But when i attach it to an object, it never looks at the camera. Why`?
If you want it to look at the camera you'd do:
transform.LookAt(_camera.transform);
This code seems to be trying to make it look in the same direction the camera is looking
(in a pretty convoluted way)
Alright thanks, that works! π
Well kinda, it looks at the camera with its back for some reaon
reason
Sounds like your model is flipped
Look at the blue arrow
That's just how text works
The "back" is where it's readable from
Oh i see... So i should just rotate it by 180 degrees i guess
No
transform.rotation = Quaternion.LookRotation(transform.position - _camera.position);
Thanks a lot ! π
Hi, I am starting to learn DOTS, imported entities package but I get this error:
Any idea why? When I inherit from the IComponentData interface, for example, I don't get any errors.
anyone can helpo
What Unity version and what Entities package version are you using?
How can I pass a T[] as NativeArray<T> in a job?
I'm trying:
GCHandle handle = GCHandle.Alloc(array, GCHandleType.Pinned);
NativeArray<float3> native = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<float3>((void*)velocitiesHandle.AddrOfPinnedObject(), count, Allocator.Invalid);
new MyJob { Velocities = native }.ScheduleParallel(query, default).Complete();
But I get:
InvalidOperationException: The UNKNOWN_OBJECT_TYPE IntegrateJob.JobData.Velocities has not been assigned or constructed. All containers must be valid when scheduling a job.
I would like to avoid having to copy the content into the native array, and I can't avoid the managed array since I get it from an API outside my control.
You can look at what this package does to achieve it, or just use it:
https://github.com/stella3d/SharedArray
is there any good reason for this?
it feels like such a strange thing to have...
Imagine if all UI elements had to be rotated 180 degrees to be visible in the standard setup
That's what would happen
If you had it the other way
oh right, I've pretty much only used world UI - that didn't even cross my mind hahah.
thanks, that makes very much sense.
I have some weird stuff going on in my code. I'm makeing a simple Higher Lower card game, but the card pictures are updating one round too late? at the start of every round, a new card number gets randomly chosen. after i click a button an animation starts playing and the card turns around etc. The number updates every round, that is working. The thing is that the picture on the card has a delay of 1 round. So the first round it's just a white sprite, but then the second round it has the picture of the card of the first round. and then the third round the second picture etc. Even though the picture replace is right under the number replace, it just completely skips that part and does it the round after. been banging my head for 3h now please someone help.
{
textDisplayNewCard.SetActive(false);
string roundName = names[nameIndex];
textDisplayName.GetComponent<Text>().text = roundName;
do //get a new random number
{
NewCard = Random.Range(2, 11);
} while (NewCard == OldCard); //repeats when newNumber == oldNumber
Debug.Log(NewCard);
Debug.Log("heart" + NewCard);
NewPlayingCard.sprite = someOtherSprite2; //replaces card with the new card
someOtherSprite2 = Resources.Load<Sprite>("PlayingCards/heart" + NewCard);
Debug.Log(Resources.Load<Sprite>("PlayingCards/heart" + NewCard));
OldPlayingCard.sprite = someOtherSprite; //replaces the old card with the new card
someOtherSprite = Resources.Load<Sprite>("PlayingCards/heart" + NewCard);
string stringrandomCard = NewCard.ToString(); //displays the random newNumber for reference
textDisplayNewCard.GetComponent<Text>().text = stringrandomCard;
nameIndex++; //cycles through the playerList
if (nameIndex == names.Length)
{
nameIndex = 0;
}
roundIndex++;
if (roundIndex > numberOfRounds) //ends the game after numberOfRounds has been reached
{
EndScreen();
}
}```
the code is a bit messy i know still working on that
oh i found the problem. Basically, because the image is inactive it doesn't update untill its active, which is all the way at the end of the animation. Then it goes back to inactive. So it updates every time at the end of the animation, which is why then the picture is always 1 round behind
https://gyazo.com/65397c550912d6f333cfde170a1814d3 got to the point where i can export my procedurally generated mesh, but when attempting to paint it with polybrush the texture look like this, is that because i havent set any uv coordinates yet?
const int rotLen = 4;
int* rots = stackalloc int[rotLen];
rots[0] = 0;
rots[1] = 90;
rots[2] = -90;
rots[3] = 180;
//Place the Layout
Layout = Instantiate(Struct, transform.position, Quaternion.identity);
//Randomize The Layout's Rotation
Layout.transform.eulerAngles = new Vector3(0, rots[Random.Range(0, 4)], 0);
Is this a good use of stackalloc, or will my unity implode
Was it necessary? Looks like unsafe coding with pointers and whatnot.
I mean I'm trying to make my game run faster, and stackalloc seemed like a way to do that
although its mostly on graphics that are hurting performance
Use the profiler.
I have my guy
although Im going to take another look
there isn't anything obvious bringing it down to 35 fps but maybe there is and im just missing it
The unsafe pointer is not necessary, you can use Span instead.
ooh what does span do
will it enfastenate my code
Span<int> rots = stackalloc int[rotLen];
let me try that and see if my code explodes
It's an abstraction to make pointers safer, but performance should be basically the same when it compiles.
You'd get real issues to resolve by evaluating the profiler else micro memory management isn't likely going to improve your frames.
what using do I need for Span to be availible?
Just System. What Unity version are you using?
This sounds like it's going down a bad rabbit hole.
2021
2021.3?
.1
Yeah, this isn't going to make any meaningful difference to performance. The Instantiate is the likely the biggest culprit, with eulerAngles assignment trailing behind it.
let me look at the profiler again
you kinda need instantiate in a procudural game
If you're doing cs private void Update() { //Other stuff that doesn't matter Instantiate(...); }your computer is going to be destroyed.
Look at the profiler. Then later consider pooling if you're intensively instantiating/destroying objects else .. just look at the profiler.
So are you trying to optimize the load time?
im trying to optimize the fact it runs at 35 fps
Hey guys, trying to write my own Rigidbody Character Controller but getting stuck on something that should be straight forward, at least in my mind π
Want to let my Rigidbody float over ground by snapDistance but I'm always on ground and sometimes not getting any hits at all
private void setGravity(bool status) => _rb.useGravity = status;
private void checkGround()
{
Vector3 pos = transform.rotation * transform.position;
// Check for ground by shooting ray from position downwards
_onGround = Physics.Raycast(pos, Vector3.down, out _groundHit, _groundCheckDistance,~LayerMask.GetMask("Player"),QueryTriggerInteraction.Ignore);
if(_onGround)
{
setGravity(false);
}
else
{
setGravity(true);
}
}
private void snapToGround()
{
if(!_onGround)
return;
if(_groundHit.distance > 0)
{
Vector3 newPos = transform.rotation * transform.position + Vector3.down * (_groundHit.distance - _snapDistance);
_rb.MovePosition(newPos);
}
}
void Update(){
checkGround();
}
void FixedUpdate(){
snapToGround();
}
If it's consistently 35 FPS, but you're not consistently calling this function, then this function is not the problem.
I mean i am calling it a lot
and it isn't consistent
it swings wildly depending on where im looking
Have you seen that this function takes a significant time in the profiler?
use the profiler or you're wasting your time
Log your ground check distance if you're always on the ground. Also your layer mask and whatnot to ensure you simply aren't casting against your object's collider. Print what you hit etc.
no, mostly in the profiler it's Camera.Render
Im looking at it right now
if your performance varies wildly depending on where you're looking, then i'd guess you have some expensive renderers
high-poly meshes, perhaps
I messed up the layout augh holdon let me get it back
or very expensive materials (that'd be something you'd know you did, though)
this bit seems to be the slowing one
Which is weird bcause the game is like 90% cubes
You may need to show more the the profiler.
That's showing the CPU rendering time, which is all about culling, batching and draw calls. Shader or mesh complexity will not affect the CPU time.
here are some things
ok well
it seems like its causing 10 ms of lag which seems bad
idk
Already doing that, problem is I'm not hitting anything and falling through the floor sometimes, getting Y-Positions slightly below 0
is there just something im missing
perhaps you can show us these stats
I mean the drawing bit seems the most expensive
also lol 1000 fps
Thought Unitys physics engine would prevent this but meh
swings wildly, but I can try
I'm always on ground and sometimes not getting any hits at all
I was under the impression that you were simply always grounded thus suggested logging the ground casting.
why are there 81900 triangles its just cubes
For cubes?
Na, starting my scene floating and falling to the ground. Having some ramps there too. Want my player to hover above the ground a bit to avoid friction between objects so I can handle it myself
perhaps you have some very hi-poly cubes
I'm not sure what you're asking then.
1.1m for what appears to just be cubes
well, that appears to just be The Backrooms
is the level one giant mesh?
or is each wall segment its own model?
each wall segment is its own object
ok
then, click on the "mesh" field of the Mesh Filter
Wonder if my approach is even the right one, calculating distance between my object and ground, deactivating gravity and setting my Y-Position with an offset to the ground.
Since it doesn't work means I'm doing it wrong π
k
Cube (Mesh Filter)
up top
that should highlight the mesh in the project view
wait, that does not do what i wanted
one mo my layout is wierd for the profiler
i want to look at the mesh asset itself
I'd just raycast towards the floor (the direction of gravity) and acquire the floor contact point then move with smooth damp towards the contact point (simulating gravity).
it looks like imported meshes will get highlighted in the project pane, at least
e.g.
yeah the cube mesh is just the basic unity cube
perhaps you are instantiating many many many copies of the wall segment by mistake?
or maybe the wall segment is very small
So not using RBs gravity for that?
no, we're very interested in the 819,000 triangles right now
ok
I was under the impression that you weren't using rigidbody physics and were creating your own physics. If with rb, you'd just use rb and hackish workarounds with disabled/kinematic physics and whatnot.
here one sec
Sounds like that's not a prefered way to do it?
It's a tough fight regardless as rb simulates physics using a rigid body whereas we're more likely to want "game/fake physics"
There are a lot of tutorials out there on kinematic rigid bodies and a few assets that have been recommended here before.
mode.Rotation is a Vector3 like this : 90,90,90.
After ther localEulerRotation assignment the eulerAngle is just 90 instead of 90,90,90... why?
What have i missed?
Yeah tried a kinematic RB Character Controller already, but hitting a wall there, wanted to start fresh with RB functions to move
var angle = new Vector3(90,90,90);
deviceRoot.transform.localEulerAngles = angle;
// deviceRoot.transform.localEulerAngles is just (90,0,0).
Why is that?
When setting localEulerAngles (or eulerAngles), Unity is calling Quaternion.Euler in the background to set the real rotation variable, which is localRotation. The rotation 90, 90, 90 is equivalent to 90, 0, 0, so Unity ends up using that.
Does anyone have any idea why objects that are Instantiated do not act the same as ones that are dragged into the scene? I have a basic little AI system, but Iβm not using any NavMeshes or anything. No variables are plugged into the scene, the AI should be completely standalone (but only works when dragged into the scene). Any ideas?
You can't. Unity uses Quaternion to represent 3D rotation. It shows Euler angles in the editor because it's more human friendly to edit, but it's always converted to Quaternion.
You could save the Euler angles in your own variable if you want to retrieve it again unmodified.
But there are very few reasons to prefer Euler angles over Quaternion.
I hate rotation stuff... dammit
E.g. i have a user defined format (json) where the user can set the objects rotation in euler.
And the euler rotation is 90,90,90.
Now when i assign it to the object, the euler rotation in the editor shows 90,0,0 and is therefore invalid.
I basically wanna take the euler anlge from the object, put it into json and load it back... i mean it cant be that hard or?
Generally your character and the obstacle would both have a collider
What kind of a game is it, 2D or 3D, how are you moving your character etc
Unity just doesn't save the Euler angles, so there are no angles to retrieve. You can only calculate them from the Quaternion, but since there are multiple Euler angles that can represent the same rotation, you can't get them all.
But just because Unity doesn't keep track of it, it doesn't mean you can't. When you load the object, you can keep the original Euler angles somewhere other than in its Transform and read it back when you want to serialize it back to JSON. Just don't expect the numbers to stay the same if you then use Unity functions to rotate the object, since that will be using Quaternion.
Probably want to adjust the stepOffset
https://docs.unity3d.com/ScriptReference/CharacterController-stepOffset.html
And maybe slopeLimit
If that's the one that controls the step height, not sure
Try it out
What i just dont get is... i mean i have a euler of 90,90,90.
I set the euler for a gameobject to exact those values : transform.eulerAngles = new vector3(90,90,90)
They are converted to quternion...
And suddenly the inspector of that gameobject shows me euler of 90,0,0.
Hows that even possible? I mean, even if the euler are converted to quaternion and back, they should stay the same right?
inspector doesnt show the actual euler, and the actual euler will convert your invalid provided v3 to a valid one
Oh it does not? What exactly does the inspector show then?
So wait a sec
are you aware of gimbal lock?
So that V3 is the offset basically?
What do i need to do in order to set the rotation to get exact those values above (90,90,90) to show up in the inspector programatically?
example, you rotate an object by -720 on x, inspector shows -720, but the euler stores only values 0-360
Since i want that the user basically just takes those values from inspector, put them into json, app is loading that json and boom the inspector shows those exact values
Quaternion is a different way to encode 3D rotation. It doesn't have the same problems as Euler angles, where different angles can result in the same final rotation. So when you convert from Euler to Quaternion, there is only one Quaternion that can represent that 3D rotation, but there are multiple Euler angles for that rotation.
so what inspector does is it compares its quaternion rotation, which results in a single -720 rotation, to the objects indentity or zero rotation quaternion and displays to you -720
A more extreme example is for example the rotation 360, 0, 0. Obviously, it's the same as 0, 0, 0, because it's just a 360 around the X axis. Quaternion doesn't have this problem, so when you convert Euler to Quaternion, that problem disappears.
euler values will not give you -720, it just cant and its not how it works
its inspector being human friendly and confusing programmers
Okay but then how do I reach my goal?
I want to set the rotation of an object so that its inspector shows exactly the V3 of 90,90,90.
In the json I would then store 90,90,90, the app loads this and sets the rotation of the object so that its inspector shows 90,90,90. How would this work?
what you can do is to convert both 90,90,90 and 90,0,0 to quaternions and compare them, if they are equal this means rotations are equal, and it doesnt matter what inspector is showing
If you look inside a prefab or scene file, you'll see how Unity saves the Transform values:
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8216044101241921426}
m_LocalRotation: {x: 0.70710677, y: 0, z: 0, w: 0.70710677} # This is the true Quaternion rotation.
m_LocalPosition: {x: -1.0077429, y: 0.19608417, z: 2.4774108}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 90, y: 90, z: 90} # This is what you see
--- !u!33 &2518793210753473943
"hint"
If this is purely for the editor, you can use the SerializedProperty API to set the m_LocalEulerAnglesHint property.
So for my inspector to read 90,90,90.... I should store 90,90,90 in a json, translate it to a quaternion on load and assign it. Then the inspector would also show 90,90,90?
It would look something like this:
var obj = new SerializedObject(transform);
SerializedProperty localEulerHintProperty = obj.FindProperty("m_LocalEulerAnglesHint");
localEulerHintProperty.vector3Value = theJsonRotation;
There is no way to get the inspector to show the rotation 90, 90, 90 without setting this internal property.
Though there may be some nicer editor API to change this that I'm not aware of.
no just test for your sanity that both what inspector shows and whats in your file are identical rotations just displayed differently
im pretty sure that will be the case
then just ignore the inspector values
No, I don't want to change the inspector value directly. I want to store 90,90,90 as euler hint in a json and assign it as rotation to an object that if I would look at the inspector.... I would also see 90,90,90 in it.
Oh god, i will never touch rotations again. My brain is just not capable of those
it will grow on you
They are saving the scene in their own format, and want to save the inputted Euler angles, for the same reason Unity does; to make it easier for humans to edit.
If instead of using vector 2 in a two dimensional game, I use x and y of vector 3, will there be a problem?
Exactly
to edit the file right
User puts 90,90,90 in a file as a readable human euler angle
yes and
So they can save the JSON and load it again and have the same original number.
The SerializedProperty method is the only way to do this.
I wanna convert that to a rotation and assign it to a object. So when i would look into the unity inspector it would also show me the same hint
unity always uses 3D transforms, so you kind of already are using vector3's
Vector3 can convert to Vector2 by dropping the Z coordinate
you'll only have problems if you try to, say, add a vec2 and a vec3
c# won't know what to do
so you'll have to explicitly convert one
Are you satisfied with my answer? It should work.
Thanks, it does indeed. Im just terrible at explaining stuff xD
The only reason I wanted to use V3 instead of V2 is because I can't subtract a value with V2
Or is there a way?
if you use Vector3.right, the subtraction will work
and then the result will be converted to a vector2
oh
How do I place red text like on this screenshot? So that it doesn't rotate and doesn't get smaller on sides because of perspective
does anyone have some advice for working with slerp, i have a ui setup so that when you press a button, it uses slerp to move all the ui to a point ive defined, which does work, but its moving in a parabola rather than in a straight line but i cannot figure out the reason for it
this is what i have for the code
and this is whats happening
slerp is not for a linear movement!
use Lerp
"Slerp" means "Spherical lerp"
imagine putting a sticker on a ball, and then rotating the ball
that's the path a slerp produces
ohmygosh yeah that makes a lot of sense, tysm!
slerp is great for camera movements
is there a nice way to reference a specific material slot on a renderer? I want to set a material property block for just one slot
i guess i could assign a reference to the material and then compare it to the sharedMaterials array of the renderer
Does anyone know resources or general tips for how to implement a drifting mechanics on a car without using a rigidbody?
i guess i would limit how quickly the car's velocity vector can be rotated
when drifting, your velocity rotates towards where the car is facing very slowly
its in the overload for SetPropertyBlock
i see the overload to actually set it
i'm just concerned about getting the right index
i guess i can just add an int field to specify which slot to target
there's probably no other sensible way to do that
can be something like
class RendererData : MonoBeh
{
public IReadOnlyDictionary MaterialIndexMap => _matIndexMap;
}
cache it once, small component, generic
overkill prob
simple Find on the array is faster
Interesting. Currently my car is always driving straight based on it's rotation. So I would need to swap out transform.forward to a variable which stores the direction of my velocity?
the problem would be if someone else accessed material/materials before this code got to run
yeah
it would compare the instanced materials to its material and think they're all wrong
yeah just IndexOf
maybe nice extension method
public static bool TrySetPropertyBlock(this MeshRenderer, MatPropBlock, Material)
{
// Array.Find etc
}
false if no mat found
also probably should be done without ref, since refs wont match on mat clones
some shader/name/id combo
Yeah, that's the fundamental problem
custom shader?
can bake some id into it
theres probably a better mechanism but i dont know
the barrel recoils a little too much, but that's another problem...
@heady iris
public Material mat;
// Start is called before the first frame update
void Start()
{
var clone = GameObject.Instantiate(mat);
Debug.Log(mat.ComputeCRC());
Debug.Log(clone.ComputeCRC());
Debug.Log(mat.ComputeCRC() == clone.ComputeCRC());
}
at least this works for simple clones
huh, I never knew about that method
turns out i was clamping its position after moving the barrel, so it wound up being framerate dependent π¬
Hi, good day.
I have a problem, i have various coroutines that do stuff and all of them share a piece of code (the yield part).
Is there any way of making that code into a function or something to prevent duplicated code?
Code examples:
// Coroutine 1
public static IEnumerator ArbolBinario(Laberinto laberinto, float probabilidadPrimeraDireccion, DireccionesEnum direccionVertical, DireccionesEnum direccionHorizontal)
{
foreach (Celda celdaActual in laberinto.Celdas)
{
// stuff
// Duplicated code
if (EjecuccionPorPresion)
{
yield return new WaitUntil(() => EjecutarUnaVez);
EjecutarUnaVez = false;
}
else
yield return new WaitForSeconds(periodoIteracion);
// stuff
}
}
// Coroutine 2
public static IEnumerator AldousBroder(Laberinto laberinto, Celda celdaInicial)
{
// Stuff
while (laberinto.GetNumCeldasSinVisitar() > 0)
{
// Stuff
if (EjecuccionPorPresion)
{
yield return new WaitUntil(() => EjecutarUnaVez);
EjecutarUnaVez = false;
}
else
yield return new WaitForSeconds(periodoIteracion);
// Even more stuff
}
}
it's small enough that I wouldn't really bother with extracting it
Its repeated in like 5 coroutines thats why it bothers my a little
i guess you could make a function that just returns EjecutarUnaVez
Could you elaborate a bit more please?
could also just make that bit its own coroutine and just yield that coroutine in all of the other ones that use it
Ummm im going to try that
is EjecutarUnaVez a bool?
yeah
Its a bit more complicated.
I have to wait either for that bool to be true if another bool is true or wait for a fix amount of time if not
Yeah but dont worry. boxfriend solution works fine and i just need it to look good so no need for better solutions.
Thanks for the help you two btw
yep, sounds good!
i have made a "custom" editor UI for my serialized objects to make it easier to see what's happening, though i have run into a problem where unity doesn't save the content. online i found something about the "SetDirty" function although i am not entirely sure about how to use it, could someone give some examples?
i have two scripts, each one of them has some stuff in it, how can i make one of them to run before the other ???
show your code.
Add [DefaultExecutionOrder(-100)] above the class name line. Unity callbacks (Start, Update etc) are called from negative order to positive, or semi random if not defined
it is likely that you're not telling Unity that you've changed things
most likely not optimal but here:
[CustomEditor(typeof(Dialogue))] public class DialogueEditor : Editor
{
private SerializedProperty options;
private SerializedProperty dialogueTextArea;
private void OnEnable()
{
options = serializedObject.FindProperty("options");
dialogueTextArea = serializedObject.FindProperty("dialogueText");
}
public override void OnInspectorGUI()
{
Dialogue dialogue = target as Dialogue;
dialogue.hasOptions = GUILayout.Toggle(dialogue.hasOptions, "Does This Dialogue Have Options?");
if(!dialogue.hasOptions)
{
Debug.Log(dialogue.speaker);
dialogue.speaker = EditorGUILayout.TextField("Speaker Name:", dialogue.speaker);
dialogue.speakerSprite = EditorGUILayout.ObjectField("Speaker Sprite:", dialogue.speakerSprite, typeof(Sprite), true) as Sprite;
EditorGUILayout.PropertyField(dialogueTextArea);
GUILayout.Space(20);
dialogue.lastDialogue = GUILayout.Toggle(dialogue.lastDialogue, "Is This The Final Dialogue?");
if(!dialogue.lastDialogue)
{
dialogue.nextDialogue = EditorGUILayout.ObjectField("Next Dialogue:", dialogue.nextDialogue, typeof(Dialogue), true) as Dialogue;
}
} else
{
EditorGUILayout.PropertyField(options);
}
}
}
yeah, i don't know how to do that
this was my first attempt at anything editor related
it's a lot, yeah :p
two start functions i want one of them to wait for the other, can it be fixed by that????
you should ask in #βοΈβeditor-extensions
I actually can't confidently answer this one
i can answer it, but i might be flat out wrong :p
If they exist at the same time, yes. The callbacks naturally won't wait if things are created later
i believe you just use serializedObject.ApplyModifiedProperties() -- but only if you use property fields, I think? https://docs.unity3d.com/Manual/editor-CustomEditors.html
Less clear on when you aren't using property fields
the solution was close, but what you said helped me realise what i had to lol. i just added
EditorUtility.SetDirty(serializedObject.targetObject);
```to the bottom of the editor script
thanks!
actually that doesn't seems to work for everything except the property fields
so i will just slide in what you wrote as well
that works
many thanks again!
Hey correct me if im wrong (which is probably the case) but:
The slider has a OnValueChange method that activates when the value changes. If i have a method in a class that gets called whenever that happens, do i need to have the slider inside the class?
The documentation says that i need to have the slider and add a listener but i have doubts
Nope you can just have the method
And i can extract the value of the slider from the method just as a parameter right?
Yep, if it takes a float your method will appear under the "Dynamic Float" section in the Inspector
Thanks for the help, it works
Hello all, I have an issue within my game where when I move the connected anchor of a hingejoint using a script, the hinge joint never moves.
Within the editor if I do this using the same script it works perfectly, however in builds it does not move the hinge. I have also installed debugging code, and can see from player.log that the connected anchor is actually changing to match what i want. The joint just never moves.
heres a screenshot of my hinge joint setup in case ive missed something obvious
is there perhaps a way of moving hinge joints which i have missed?
share the script?
!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.
public class TargetController : MonoBehaviour
{
[SerializeField] private Transform _targetHolder;
[SerializeField] private HingeJoint _targetAnchor;
[HideInInspector] private float _amplification = 1;
[HideInInspector] private float _z;
[HideInInspector] private float _zDifference;
[HideInInspector] private Vector3 _anchorIntended;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
_zDifference = _targetHolder.position.z - _targetAnchor.connectedAnchor.z;
_z = _targetAnchor.connectedAnchor.z + (_zDifference * _amplification);
_anchorIntended = new Vector3(_targetAnchor.connectedAnchor.x, _targetAnchor.connectedAnchor.y, _z);
_targetAnchor.connectedAnchor = _anchorIntended;
Debug.Log(_targetAnchor.connectedAnchor);
//Debug.Log(_anchorIntended);
_targetAnchor.autoConfigureConnectedAnchor = true;
_targetAnchor.autoConfigureConnectedAnchor = false;
}
}```
it really doesent do much
if im honest i think im doing this just completely wrong, i mean it works but this method is awful
Not really an answer to your question but:
[HideInInspector] private float _amplification = 1;
[HideInInspector] private float _z;
[HideInInspector] private float _zDifference;
[HideInInspector] private Vector3 _anchorIntended;```
Why did you need to make these fields, why not just local variables? You even went out of your way to add an extraneous `[HideInInspector]`
anyway - what are you trying to actually do with this code
yea my formatting is kinda odd not sure why i did it like that, made this ages ago
I mean that's not formatting, it's a functional difference of using instance variables instead of local variables.
i have a chain of 2 hinge joints which im using to pivot an object, imagine holding a piece of paper at the top and moving your hand back and forward.
To then move this chain of hinge joints I move the top one by changing its connected anchor position. This works fine in the editor however doesent work at all in builds
shooting range target?
precisely
Can't you just move the top thing via the physics engine and everything will work as expected?
although it seems like you don't have a connected body configured for the joint(s)?
how would i do that? I couldnt figure that out when i originally made this so did it this way
via Rigidbody velocity or MovePosition
yea i dont use a connected body i dont really know how they work either. Hinge joints are a bit of a mystery to me
You would need each piece to have a Rigidbody
and connect them to each other via the joints
that's the correct setup
hm ok, at the moment my bottom hinge is connected to the top hinge with a connected body. Where would I connect the top hinge to?
This is my hirearchy, the child called target is the actual bit of paper
Guys
Quick question
When i serialize a custom class, does unity automatically constructs the class?
do i need to call a constructor?
Unity will automatically construct the object when deserializing a serialized field
awesome, ty!
In the context of having an slide and a TextMeshPro that shows its value, having this inside the text that its supoused to show the slider value:
public TextMeshPro PorcentajeText;
void Start()
{
PorcentajeText= GetComponent<TextMeshPro>();
PorcentajeText.text = "0%";
}
public void UpdatePorcentaje(float newValue)
{
PorcentajeText.text = Mathf.RoundToInt(newValue * 100) + "%";
}
I get this problem: NullReferenceException: Object reference not set to an instance of an object in the UpdatePorcentaje line.
Any idea why? (Note: The method is asigned in the OnValueChange of the slider.
PorcentajeText did not have a value. If you drag-drop the TMP, then you don't want the GetComponent in Start that will overwrite its value
You suggest me to drag the object rather than get it?
Well your field is public for that reason, I guess
So it's visible in the Inspector, so you can drag-drop
The script is in the text that i want to check and i made it public to try to make it work but i will try this
It's very unlikely TextMeshPro is the correct type btw
GetComponent searches the object this script is on, not another one. So if you don't have a TMP aside this script, GetComponent will fail and return null
You probably want TMP_Text
If the text is in the object that has the script it should work then?
Maybe, what's the text though, you might be trying to get the wrong type
What does it look like in the Inspector?
Yeah it was the Type, sorry for the confusion, PraetorBlue was right.
(A lot of TextMeshes to know xd)
Thanks for the help.
Cleanup, since you now use GetComponent there's no need for the field to be public, this will prevent bugs in the future
Bugs where you don't remember how the script works, you drag-drop and it doesn't work
You'd just get slightly harder to debug errors if the component is missing and using get component π
In a way, you could consider inspector referencing to be an explicit reference whereas get component would be implicit (it's implied that this object should have the necessary component).
Hey! I am new to unity and I am trying to learn it with
Game Maker's Toolkit's tutorial (https://www.youtube.com/watch?v=XtQMytORBmM). Doing everything with video, I encountered small problem. Doing flappy bird game, my pipes are not spawning as I would wish. Basically it looks like this:
GMTK is powered by Patreon - https://www.patreon.com/GameMakersToolkit
Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and then give you some goals to learn ...
wait I cannot send that file in video format
the script looks like this
using System.Collections.Generic;
using UnityEngine;
public class PipeSpawnScript : MonoBehaviour
{
public GameObject pipe;
public float spawnRate = 2;
private float timer = 0;
public float heightOffset = 10;
// Start is called before the first frame update
void Start()
{
spawnPipe();
}
// Update is called once per frame
void Update()
{
if (timer < spawnRate)
{
timer = timer + Time.deltaTime;
}
else
{
spawnPipe();
timer = 0;
}
}
void spawnPipe()
{
float lowestPoint = transform.position.y - heightOffset;
float highestPoint = transform.position.y + heightOffset;
Instantiate(pipe, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
}
}```
can someone help with making it look like in video? 26:10
oh I didn't see that
also your video needs to be mp4
First clarify in words what's the issue (although it's obviously spawning to the left of the bird that's the issue)
yes i converted it
Yeah, move to beginner coding.
alr
okau
i'm completely new to unity and when launching my first project i have an error at the bottom, how do i go about getting rid of this or is this expected seeing as though i haven't done anything with it yet?
Is it related to PlasticSCM?
(hint: read the full error)
open the console window
yes it is
go into package manager and upgrade the Version Control package
or uninstall it if you don't plan to use it.
thank you so much, really appreciate your help :)
nice to see unity is shipping new editor templates with broken VC package
In the below Location class, specifically when the constructor is called, what is going on? There is an expression body member operator that is initializing the object as a string?
public class Location
{
private string locationName;
public Location(string name) => Name = name;
public string Name
{
get => locationName;
set => locationName = value;
}
}
It takes a parameter string name and it's just assigning that parameter value into the Name property setter
the ultimate effect here is you will have a Location object with locationName set to whatever string was passed into the constructor
Hello, I'm making a WPF app and I would need help to review my code, I know it's Unity but I don't know elsewhere to ask this, thanks in advance
Compiler shorthand for
public Location(string name)
{
locationName = name;
}
Ask in the C# server
!cdisc
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
!cdisc
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Wow really weird. I was used to expression body members being assigned the expression on the right; not the other way around where an expression is assigned a method parameter.....
Hey guys, im working on a 2D game. The project is still very small and my fps is absolutely garbage.
I got 230 with the player character not moving, without any 2d lights on the scene, 160 with the character moving and if i enable lights.
Ive gone into the profiler, enabled method names, and my methods are okayish, the worst one takes 0.018ms to complete so... im pretty lost as to what is happening. Any tips are appreciated
there's going to be some constant cost per-frame
so your game won't go to 3,000 FPS even if you're just rendering one square
i would only be concerned if the game starts bogging down significantly as you add small amounts of content
Sure. I can understand that. but it seems utterly ridiculous to have this amount of FPS with what im doing
230 fps is a lot of frames per second
the cpu is screaming at the gpu and the gpu is screaming at the cpu and it's desperately working to fill the screen with pixels 230 times per second
this is peaking me at almost 30 fps on a 2D game, with an NVIDIA 2060 and a ryzen 5 3600. Seems pretty crazy to me
Your hardware (and possibly background applications, like a antri-virus running a scan or Steam downloading) can have a big affect on framerate as well - both the Profiler, and just the Editor in general also add overhead, every window (like the Scene, Game, Hierarchy, custom editors, etc) also add overhead (albeit, at different rates) so its good to test your frames in a build as well, which should have better frames, depending if you have VSync enabled or limited the Application.targetFrameRate, or playing in a different Screen.Resolution, all can affect framerate, in addition to the limitation of your hardware
that shows 200 fps. Profiling in the editor is error-prone. Your player loop is running in 5 ms and almost 80% is spent doing something with the UI, so if you must optimize look at ways to avoid creating dirty geometry (nested Canvases, fewer updates, etc)
but profile an actual build first
I saved a few ms in one of my games when i realized that i was never actually deactivating UI that wasn't shown...
it was SmoothDamping towards 0 alpha, and it was supposed to deactivate the panels at 0 alpha
...so it'd wind up at like 0.0006 alpha, slowly trickling towards 0, and never actually deactivate
Did you end up fixing that with a Mathf.Approximetly(..., 0) or just checking if its < some small decimal?
On a build, it is capped at 60 FPS
Is your Application.targetFrameRate also capped to 60? (maybe by default, if you didnt change it)
if desktop, disable vsync. If mobile, that's likely the max refresh rate of the screen and you can't change it
possibly
i just set Application.TargetFrameRate = 300 on a script, on awake(). and it caps me at 120 now
you can attach the profiler to a build
yeah... okay. I just set vSync to 0 as well and with 30 light sources around the scene i dont get less than 120 FPS. So i guess not horrible
uhm.. how?
i forget the specifics
you can look it up, though :p
i mostly just profile in the editor because i care about relative cost, not absolute cost
hmm, my function is taking 80% of the player loop
uhm.. i can understand that
yeah i can't even find any of my methods there
so i guess they are good
its crazy to see how much overhead unity is actually taking... and how expensive 2D lights on the URP are. pretty crazy stuff.
but yeah... i guess there isn't a whole lot i can do about it
if I have items that are represented with SOs, and then I have corresponding prefabs associated with them (like a Stick SO with crafting data, and a Stick prefab that has a sprite renderer so sticks can be placed throughout the world), how do I combine these two with an inventory for a complete system? I thought about using a dictionary and an array, where the array stores SOs and the dictionary's k/v pair is SO/prefab, but then I didn't know how to handle items that have a stack size (or how to handle serializing the inventory, but that's a problem for later)
am I mostly on the right track or am I way off? what am I looking for here
not sure if this is the spot for it, but if anyone has tips on how to do CI/CD for mobile, that would be appreciated
my own opinion is this: if you think of scriptable objects as a data asset, then another way you could see prefabs is as a way to display that data. You could call these things "model" and "view" respectively, if you want to follow MVC, MVVM, or other programming patterns
So, in terms of how to store an inventory with that in mind, think about what you may want to add to the SO in order to make your life easier on the "view" side of things. Or, think if you need to use SO's at all, there could be other options. Personally, I think i'd have a datastructure that encapsulated the information I want to store (maybe the SO) and the quantity of that item
This simplifies the problem down to being a one dimensional list instead of multiple containers and container types
other things you could add to your SO for your system are the UI Image you want to use to display the item, the name of the item, other data you want to show
so yeah, i like to use prefabs in a way that is modular, where you could pop in whatever SO you want and have it change the resulting UI element
Moving this to this channel
I have a 2d isometric grid and tilemap that has grid tiles painted on it. I want to put my pathfinding script in here which uses A* as well as the NPC script that uses the pathfinding.
Here is my Pathfinding script and where i call on it in NPC.cs. sorry in advance for the dump lol. the prints show it scanning 9000 tiles but never returning a path that isnt empty
https://pastebin.com/3TQN2qn7
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.
Make another SO that represents the item abstractly and have it reference any other SOs (eg with item config/variants) and prefabs (for display/interaction in the world). Then put that combination SO in your inventory list/dictionary and use it to have unified access to all its component parts. You can also make any one of the existing data objects serve as the combination object.
this is an interesting solution, I'll definitely try it out
is that typically how they're handled? I'd look at videos about them but they're all over 30 minutes long and I can't really get the energy to sit through them
There is no typical architecture, different types of games have different needs. SOs and prefabs are just an easy way to make all this config editable/explorable by designers. I'd be careful with creating too many different SO types, can get confusing/messy. Its a good place to start though, as you can always build tools around an architecture that is already properly modularized and composable.
I'd been wanting to explore SOs more in depth ever since I saw people were using them in place of singletons, which blew my mind. I'll keep all of this in mind and thanks for pointing me in the right direction
please, before you get excited about that "SO as singleton" use case, be sure you actually understand what a singleton is, and why SOs are NOT a replacement for singletons. SOs can fix your singleton infested codebase, but only if you use them right, they can also make it all much worse and create an intractable mess of editor references and hard to debug code flow.
if you use a singleton primarily to get easy access to an object instance you are misusing the pattern
I'm trying to find the code for the Move function of the CharacterController class, because I'm working with some movement code I found, but wanted to integrate it with my custom character controller scripts. Where can I find it?
afaik its not public
Damn.
Here's the thing, I'm using AddForce to move my player controller, and I think that's interfering with the movement scheme.
character controller and force simulation are incompatible
Yeah I figured.
@leaden ice sorry to ping but i have a question on this, ive now set the top hinge to move my rigidbody move position, however this causes the target to rotate and then get like stuck in the ceiling lol
void Start()
{
rb = topHinge.GetComponent<Rigidbody>();
}
void Update()
{
float _zDifference = _targetHolder.position.z - topHinge.transform.position.z;
float _z = topHinge.transform.position.z + (_zDifference * _amplification);
_destination = new Vector3(topHinge.transform.position.x, topHinge.transform.position.y, _z);
rb.MovePosition(_destination);
}
That's why I need to change some stuff around.
I'm looking into CPM-style movement (from Quake 3 Arena), but the guy uses the built-in CharacterController component. The collider that it generates interferes with the projectiles I fire from my weapons.
don't ping if you are sorry π
im just trying to be polite π
then dont ping
π ±οΈruh
ever so sorry π
you could have a look at KCC if you are serious about your movement, it has a great implementation for all the tricky bits (CharacterMotor) and a very nice example controller to learn how to use it properly (https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131)
it's been nice for me, so far
i like how you can swap out the controllers
i'm planning to use that to implement different movement abilities
haven't met a person that doesn't love that thing
i am working on a object pool for my game and i am having a problem that is when the queue starts from the top again after it reachs last object my bullets dont collide with anything ..here are the function from both the scripts ``` public GameObject SpawnObject(string tag)
{
if (!objectPoolDict.ContainsKey(tag))
{
Debug.LogWarning("Pool with tag " + tag + " doesn't exist.");
return null;
}
GameObject spawnedObject = objectPoolDict[tag].Dequeue();
spawnedObject.SetActive(true);
return spawnedObject;
}
public void DespawnObject(GameObject objectToDespawn, string tag)
{
objectToDespawn.SetActive(false);
objectPoolDict[tag].Enqueue(objectToDespawn);
}
private void SpawnBullet(Vector3 position, Quaternion rotation)
{
GameObject bullet = ObjectPooler.instance.SpawnObject("Bullets");
if (bullet!= null)
{
bullet.transform.position = position;
bullet.transform.rotation = rotation;
bullet.GetComponent<Bullets>().BulletData = weaponData.BulletData;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (isDead)
return;
isDead = true;
var hittable = collision.GetComponent<IHittable>();
hittable?.GetHit(bulletData.Damage, gameObject);
if (collision.gameObject.layer == LayerMask.NameToLayer("Obstacle"))
{
Debug.Log("Hit wall");
ObjectPooler.instance.DespawnObject(gameObject, "Bullets");
HitObstacle(collision);
}
if (collision.gameObject.layer == LayerMask.NameToLayer("Enemy"))
{
ObjectPooler.instance.DespawnObject(gameObject, "Bullets");
HitEnemy(collision);
}
ObjectPooler.instance.DespawnObject(gameObject, "Bullets");
}```
I may need to look into this a little later. π€
It looks interesting.
Hi, I am following a tutorial on yt on how to make a 3d survival game, and i am on the inventory episode, and for the code, i am using IBeginDragHandler, IEndDragHandle, and IDragHandler, but when i drag, the object im dragging disapears until i let go of it, I will attatch a video of it. How do i fix this
This is my code
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class DragDrop : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler
{
//[SerializeField] private Canvas canvas;
private RectTransform rectTransform;
private CanvasGroup canvasGroup;
public static GameObject itemBeingDragged;
Vector3 startPosition;
Transform startParent;
private void Awake()
{
rectTransform = GetComponent<RectTransform>();
canvasGroup = GetComponent<CanvasGroup>();
}
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log("OnBeginDrag");
canvasGroup.alpha = 1.1f;
//So the ray cast will ignore the item itself.
canvasGroup.blocksRaycasts = false;
startPosition = transform.position;
startParent = transform.parent;
transform.SetParent(transform.root);
itemBeingDragged = gameObject;
}
public void OnDrag(PointerEventData eventData)
{
//So the item will move with our mouse (at same speed) and so it will be consistant if the canvas has a different scale (other then 1);
rectTransform.anchoredPosition += eventData.delta;
}
public void OnEndDrag(PointerEventData eventData)
{
itemBeingDragged = null;
if (transform.parent == startParent || transform.parent == transform.root)
{
transform.position = startPosition;
transform.SetParent(startParent);
}
Debug.Log("OnEndDrag");
canvasGroup.alpha = 1.1f;
canvasGroup.blocksRaycasts = true;
}
}`
!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.
probably because while you move it's going behind the background
You need to post the !code onto a code service next time - it's too large.
Other than that.. the something that's happened in OnBeginDrag is making it not visible and OnEndDrag making it visible again.
What immediately caches by eyes are parenting, and alpha values. Since alpha value is 1.1f in both cases, it doesn't matter much but the parenting might be the issue.
π 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.
Using photon, my code is having this issue for some reason
It has legit never been a problem in the past
My code worked perfectly like this for months now
and now its telling me theres a problem
You've probably got another class called Player
Else you'll need to show us the error line. The error message means little by itself.
So basically, every time a player joins a room it will assign a player variable to the player who joined
and then I can use that to do other things
this is a code channel. I'd ask in #πβart-asset-workflow
or possibly #πΌοΈβ2d-tools
thanks @somber nacelle
and it has worked flawlessly until today
will repost there
Move your mouse over Player, what's the type?
So it isn't a Photon.Realtime.Player.
no
And you're attempting to pass it to the base method which requires a Photon.Realtime.Player.
you can't cast Photon.Realtime.Player to Player
well its worked before so
not trying to say you're wrong
You've probably redefined the Player class.
As I suggested well above.
alr
if you're sure then dont doubt yourself
ill check
but to use player inplace of that namespaces player, there would have to be references
Likely you did not have a Player class before and it was referring to photon player class prior
alrighty ty
yeah i am legitimately stupid
I checked
so sorry for wasting your time
issue is fixed lol
It's discord, ask and receive help.
I have a code for my character to climb ladders by setting the collider of an object to levitate the character but it doesnt work and i dont know whats wrong?
lmk if you want me to send the code
when asking for help with your code you should just assume you should send it. !code
also check out #854851968446365696
π 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.
you're gonna want to re-read the bot's message there, mate
hello I need help with a bug I am having in my game. So when I start the game in the main menu and start either the game or the tutorial it runs fine no issues but if I pause the game go to the main menu and decide to go back to either one of the scene it freezes but if i pause and unpause the game it works fine again. I wanna know how i can fix the freeze bug when loading back into that scene from before.
I would like to do a call and show anyone if anyone is willing to help me (I am sorry for asking of this)
you probably don't want these lines:
else
{
isClimbing = false;
GetComponent<Rigidbody>().useGravity = true;
}
because if this object is touching more than one trigger collider every frame but only one of them has the Ladder tag then those lines will run
also you need to actually say what isn't working
thought i did here soory
when the player walks to the ladder object it doesnt let it climb it act like a normal collider
sounds like it's probably not a trigger collider
whats the code?
GetComponent<Rigidbody>().velocity = Vector3.zero;wouldn't this line just make your character sit still? (row 47)
it would, but they are moving up the ladder via transform which means that line doesn't really matter
that's the thing it doesnt say what code it is i dont have any red errors or yellow errors but the issue is caused and i looked online what to do
I didn't recognize that, lotta bloat in there. good catch.
im so confused and i cant find the dang solution
it ensures the character is moving up
could i see it?
i have 10 different scripts of code what would be easy to send you without clogging the chat with code
@plush valve
@plush valve had you set a Debug.Log in the trigger stay function to make sure it's registering?
it sounds like when you go back to the main menu you aren't setting timescale back to 1
the part which involves the pausing
yes
what did you name the scripts?
!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.
Did you attempt boxfriends solution J.OB?
yes i removed that part but its still the same
did you make sure that the collider actually is a trigger collider?
I'd suggest putting some debug logs in your code to see what's going on. Specifically in the TogglePause method, outputting the new state of the game(paused or not).
you could add a check to see if the PauseMenu scene is currently loaded before pausing or unpausing the game
I dont see a trigger collider
it's a checkbox on the collider
and you are certain that it is acting like a solid collider instead? if so you probably need to show the regular movement code
alr
its the 3d third person movement code
when creating a project
i used it as a base for the project
how would i do that im not the best coder
also ( with the help of boxfriend i think the thing that is causing the issue is around here https://paste.ofcode.org/zrx5n5RCwmbBwwzrgVjxUb)
you need to actually call that method when you return to the main menu
set time scale 0 to false
with the trigger set on the character walks through the ladder
if the character did not have a trigger collider before then it shouldn't now. the ladder would be the one that needs the trigger since you are relying on OnTriggerStay/Exit and you're supposed to be able to walk through a trigger because it's not solid
anyone has any idea why after i object pool my bullet prefab it doesnt detects any collisions?
Perhaps some of the rb/collider properties are modified during pooling?
Also, are you sure that it doesn't actually detect collisions and it's not a fault in your logic?
the weird thing is that it works when it go through the queue for the first time
What queue?
{
if (!objectPoolDict.ContainsKey(tag))
{
Debug.LogWarning("Pool with tag " + tag + " doesn't exist.");
return null;
}
GameObject spawnedObject = objectPoolDict[tag].Dequeue();
spawnedObject.transform.position = position;
spawnedObject.transform.rotation = rotation;
spawnedObject.SetActive(true);
return spawnedObject;
}
public void DespawnObject(GameObject objectToDespawn, string tag)
{
objectToDespawn.transform.position = Vector3.zero;
objectToDespawn.transform.rotation = Quaternion.identity;
objectToDespawn.SetActive(false);
objectPoolDict[tag].Enqueue(objectToDespawn);
}```
the queue of the bullet prefab
Ok, doesn't seem like there's any issue in the spawning/despawning itself. I'd check the faulty bullet's properties in the inspector. There are only that much reasons a collision could not be detected.
{
if (isDead)
return;
isDead = true;
var hittable = collision.GetComponent<IHittable>();
hittable?.GetHit(bulletData.Damage, gameObject);
if (collision.gameObject.layer == LayerMask.NameToLayer("Obstacle"))
{
Debug.Log("Hit wall");
ObjectPooler.instance.DespawnObject(gameObject, "Bullets");
HitObstacle(collision);
}
if (collision.gameObject.layer == LayerMask.NameToLayer("Enemy"))
{
ObjectPooler.instance.DespawnObject(gameObject, "Bullets");
HitEnemy(collision);
}
ObjectPooler.instance.DespawnObject(gameObject, "Bullets");
}```
What's isDead?
Is this code not on the bullet?
I fixed it with the freezing issue
cool
thank u for who tried to help @plush valve @somber nacelle @cosmic rain you guys were big help 
wait i forgot why i put it there lemme check :V
dammit that was the issue Thanks man m blind af
Im following a photon tutorial and i made these override voids OnPlayerLeftRoom() and OnLeftRoom() They do not work. Error: No suitable method found to override.
Then you're probably not inheriting from the correct class.
wdym sir
it means exactly what I said
Probably too early to start with networking, if you don't understand inheritance
clearly not if you're inheriting from monobehaviour
Then you would know what the error tells you.
ah
Probably not.
hey i have another problem
just ask a question
Then why did you ping someone
because i was about to ask the question
Christ
and then im like: "oh lemme debug before I make myself look stupid"
alr
i debugged
and now i know
Hello there, probably this is not the right channel to ask, but how much space does github free plan allow to have on a private repo?
those two override functions are not being called
look it up
hey im getting this error: NullReferenceException: Object reference not set to an instance of an object
Weapon.Aim (System.Boolean p_isAiming) (at Assets/Scripts/Weapon.cs:300)
Weapon.Update () (at Assets/Scripts/Weapon.cs:115)
in this script: https://hatebin.com/fowikbjthc
I have looked it over and I have no idea why it's not working. If someone could help that could be great
is there any better free solution to github (not unity collab)
Github only says about the push limit, not the actual repo limit
u making a shooter
cool
ill take a look at the script
thanks
it seems like the item in the list does not exist
the scope specifically
it does exist
you have to assign it in your inspector
you need to assign a scope or just add a null check
thats what I meant though...
lol yeah
ui_scope = GameObject.Find("HUD/Scope"); this will override anything that is assigned anyway
Yes
where is your question..?
not the #region SUS π @true palm
I mind. I'm not going to answer a question where literally no context is provided
Perhaps you could just type 1 paragraph instead of 50 unrelated messages
hey, I have to go for a little. I'm having dinner. If someone figures it out could you DM me the answer? If so that would be great
You have already been answered.
we left some responses here
Could be wrong, but I think there's no repository limit(which would be weird). Only file size limit.
In this script: ```cs
using System.Collections;
using Photon.Pun;
using Photon.Realtime;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class PlayerListItem : MonoBehaviourPunCallbacks
{
// Start is called before the first frame update
[SerializeField] TMP_Text text;
Player player;
public void SetUp(Player _player)
{
player = _player;
text.text = _player.NickName;
}
public override void OnPlayerLeftRoom(Player otherPlayer)
{
if(player == otherPlayer)
{
Debug.Log("Destroyed Player Object");
Destroy(gameObject);
}
}
public override void OnLeftRoom()
{
Debug.Log("Called OnLeftRoom Fucntion");
Destroy(gameObject);
}
}
Boom
Context
I have no idea how #archived-networking works
That seems to be the case, Github only talks about file push size limit and not repo limit. Thanks!
This is a programming channel
I dont know anything about multiplayer though, are those functions rom PUN namespace or are they your own fucntions?
Then why are you asking these random questions specifically to me, without any context, in the wrong channel, and as multiple posts instead of paragraphs? Are you trying to be as obnoxious as possible?
Then donΒ΄t ask those questions here...
they are from the pun realtime
sorry sir
I think photon has its own discord, you may want to check that out
i just get a bit antsy at night cuz my ADHD medication wears off
So I've got a UI bug in my game that I can't figure out, but I have figured out that it has something to do with how I'm calculating the width of UI elements. I've tried three different ways (all shown in the attached video) to find the width of this UI element, but for all of them it changes based on the screen size, and I don't know why. All I want is a consistent width of the UI element, no matter what the screen size is. Here's the code I have in OnDrawGizmos that's showing what is in the attached video:
{
RectTransform rectTrans = AgentTabs[0].GetComponent<RectTransform>();
float width = rectTrans.rect.width;
float sizeDeltaWidth = rectTrans.sizeDelta.x;
float rectSizeWidth = rectTrans.rect.size.x;
Gizmos.color = Color.red;
Gizmos.DrawRay(AgentTabs[0].transform.position, width * Vector3.right);
Gizmos.color = Color.blue;
Gizmos.DrawRay(AgentTabs[0].transform.position + (32 * Vector3.up), sizeDeltaWidth * Vector3.right);
Gizmos.color = Color.green;
Gizmos.DrawRay(AgentTabs[0].transform.position + (64 * Vector3.up), rectSizeWidth * Vector3.right);
}```
also, here's the inspector settings of the canvas it's attached to
MOBA Character/Ability Architecture
not sure if this goes in a different channel. There's so many channels lol.
So I'm trying to display text on this sign sprite, and google said I should use a TextMesh component on a child object. Only problem is, I can't seem to set it to the right layer. It's there, but it's behind my background object.
The components don't seem to have a field to set that, and setting the Layer for the object itself didn't do anything
If it is a normal TextMesh object and not a UI object, you need to move it forward in the world
Like, z transform? No values work
yeah, z, try going to 3d view and moving it in front of the sign
It seems to be working fine when i try to recreate it, not sure why
it does glitch out a little bit when the two objects are close though, maybe try pulling the text object further forward?
@languid crane when you recreated it, is your text visible from both sides if you go to 3d view?
yes