#archived-code-general
1 messages · Page 325 of 1
the only thing im using the agent for is literally just input for the AI, to know where its next position should be
Unfortunately the extra data that varies between objects of a SavedObject is represented in the form of a string[]
did you set updateRotation to false on the agent?
So uh... Y'know, it'd really suck to write data into a string[] half blindly, the only way to know which index holds what is to check the Save/Load function of the object
Not too sure then if you're not using setDestination in conjunction, but in general I try not to really mix both of those things together as I always get funky results.
yep, in the test code i set updatePosition and updateRotation to false. This time i also tried agent.isStopped = true; but it still has the bug. Even tried setting everything to 0 in the component
well in this test code, im literally not doing anything to the agent besides whats shown. Its just a collider, rb, navmesh agent, my script above, and thats all
ill likely just report it as a bug and use the navmesh agent as a child object. Not a big deal
Have you tried disabling the component as you try to use rb methods?
did you try using rb.MoveRotation instead of setting rotation directly?
Usually if I want to do some rb/agent combo, I switch both on and off when needed
enemy ragdoll stuff, ect
move rotation still causes it yea, but i just remembered transform.rotation works fine with it
odd transform.rotation should break rb.rotation
i do use set destination in my actual AI logic, so right now disabling it would cause errors
it seems like disabling the component does work but then also cant really use the agent. Putting it on a child object is just easier for now instead of remaking this
Hello @latent latch, can we do IK with the circular mesh ?
I don't see why not?
this is reallllly vague even with the messages below. Using a string to save data doesnt really mean anything unless youre just doing a ton of reflection in this. You should show the code or more of the setup if you want a proper answer
I've only done rigging in blender though, and unfortunately ik stuff gets filter out when porting to unity so you usually need to just do the animations fully there
Can you teach me how to ? Which package do i have to use...
unity does have its own animation package but Ive not touched it
the mesh has nothing to do with your IK. IK just uses the bones, and directly moves the transforms. Your mesh just so happens to move along at the same time
More of an #🏃┃animation question though
I dont think we cant do animation there are many shapes
This is a SavedObject
public struct SavedObject
{
public int id;
public int instanceId;
public int instanceCode;
public Vector3 position;
public Quaternion rotation;
public string[][] data;
public SaveableObject loadedObject;
}
Even though I know how to do the stuff, I'm not the best person to ask for the stuff as it's one of those things I do once in a blue moon.
animation also includes animation rigging, which i assume is what you mean by IK. Otherwise im not sure what you're doing
https://www.youtube.com/watch?v=l6hDpFaXEcY Im making this game clone, any suggestions ?
honestly, you could just make animations for these
trying to make an all encomposing solution through animation rigging sounds like a pain in the ass either way. Like you have 3 bones for that triangle, then suddenly want to go to that straight line, you cant just delete a bone.
And this is a saveable object, stripped down to the very least I need to show
public class SaveableObject : MonoBehaviour
{
public int SaveID;
public SaveableReference savedObject = new SaveableReference(null);
public MonoBehaviour[] saveableBehaviours;
public SavedObject Init()
{
SavedObject save = new SavedObject(SaveID, transform.position, transform.rotation, new string[saveableBehaviours.Length][]);
for (int i = 0; i < saveableBehaviours.Length; i++)
{
save.data[i] = ((ISaveable)saveableBehaviours[i]).OnInit();
}
return save;
}
public SavedObject OnSave();
public void OnLoad(string[][] save);
}
You see what this does? If you spawn one you merely get an init state of the object
Which means that it doesn't change no matter how you call it
There're many shapes, how i can make animations work ? Make animation each shape right ? @lean sail @latent latch
Each prefab always gives the same save on init, that's the problem...
Init should have some parameter of data you pass into it
Read the data from your list, if it's some sort of prefab you init that prefab and throw it into the scene at some position
Since the SaveableObject script isn't intended to be unique for each prefab existing in the game, it's not really reasonable to do so... '^^
I like to make a table for prefabs such that an ID represents a prefab. So, if prefab is ID 4, when you save that prefab for next sessions you look up the prefab ID from the table and figure out from there what it should be.
The SaveableBehaviours might vary for each prefab
That's exactly what I do lol
Thing is that each ISaveable treats their data differently, and each prefab might have different ISaveables
How are you managing to cast from MonoBehaviour to ISaveable?
Just cast it, why?
maybe, but games like these probably had a small team working on it to quickly pump it out asap. I dont see any solution which you'd like as an answer.
I think no matter what you're gonna be making some animations, but maybe you can use a line renderer to avoid parts of it. Like the larger triangle and smaller triangle can have the same logic as a line renderer, but would require different animations.
I usually have a save/load method for each specific data type like Weapons, Entities, and GameStates
Wdym for each specific data type?
cannot MonoBehavbiour does not implement ISaveable
Nope, the thing is that it might
the line is valid c#, its just not guaranteed to work if you plug in the wrong reference
Monobehaviour itself doesn't, but things that inherit it might
Yeah
cannot cast unless it is guaranteed. you can use as though and check for null
I don't care about upgrade variables and item specific values if what I'm trying to save and load is an entity, so I try to group them somewhat up.
So I extend from my normal save class to compensate for the grouping.
So all your weapons have the save structure for a save file, all your entities too and so on?
exactly
For me it's that each ISaveable treats it their way
Probably more ways about it by just doing a single super class and comparisons, but I like the class constraints.
You can't unite the save of the attached Creature script, EffectManager, Inventory, Pickup, Destructable, Projectile, Constructs etc... That's the case in my game
Being the kinda sandbox game this is, I don't think that it's gonna go well categorising them into a limited few groups
Maybe I could make each ISaveable provide some sort of settings struct tho? A more user-friendly representation of the raw data array in the background
Just I'm not quite sure how to make an array in the inspector display multiple data types... And not quite sure whether I can make it save the settings properly either
It'd probably require some custom editor stuff
Can try that, otherwise yeah, probably working with custom editor stuff
Not sure why you need it displayed in the editor though
Good point
I could hard code it in the scripts
I just sort of prefer not hardcoding it in the scripts
Thanks, i will try line renenderer
Thanks tho, this might be really useful
Hi, I am sending files to the server using WWWForm form = new WWWForm(), I send .png file like this form.AddBinaryData("design_img", imgbytes, filename, "image/png"); like this, I want to send a file specifically .fbx file using form how can I do this?
do the same. the mime type is application/octet-stream
I have tried this form.AddBinaryData("fbx_file", fileBytes, "FBX", "application/octet-stream"); and I got the file but not the extension(.fbx), I am not sure if this is from the backend.
@knotty sun
that will be the backend
Hey guys. Im working on an inventory system and im having trouble connecting with the UI.
I have two inventories atm, one created by the player, the other by my game manager(for now) .inventory is a normal C# object.
Then i have my UI in a different scene and it has an inventoryui script Which is a monobehaviour.
Im having trouble letting each inventoryUI know what inventory they belong to
You can either hardcode it by creating separate monos for each that extend a base InventoryController class, and then just have them populate by passing some the inventory they want to a base Initialize function
there's so many ways you can do it, but if you can I agree with Osteel and just hardcode it
Or you can use a single inventory UI that is passed the items when opened, by whoever triggered jt
in a perfect world your inventoryUI and inventory should be completely independent
Or you can have a single inventory controller that is used for both (as you have it now) and have an enum field that lets you specify which inventory to sync up with ,and just use an if statement to grab what you want.
The ui is listening to some event actions the inventory invokes whenever things happen(item added, item removed...
So, for me not to be destroying/instantiating, or dealing with object pool for my items i would really like to be able to let an InventoryUI monobehaviour know what Inventory(normal C# object) it is linked to
maybe i can emit a signal whenever i create an inventory and some other class can listen and set up the references?
If I made it all independent, my InventoryUI would have an Assign(Inventory inventory) method which grabs the Inventory reference you want to bind to and then subscribe to Add/Remove events
yeah i get that, but its complicated for my Player and GamManager to get a reference to an InventoryUI to call the function as they are all in different scenes
not impossible tho, just probably a bit spaghetti with my current system architecture
Well, this is where the question of do you have multiple InventoryUIs per scene
if not, make InventoryUI a singleton
In that case make some manager that holds a list of InventoryUIs such that you can Request() one
not sure my problem is relevant for this channel
but when i install mongodb drivers through visual studio, including the drivers work fine. but when i try to run the project in unity, the drivers can no longer be found
yes, you cannot install via VS as the .csproj files are maintained by Unity. You need to copy the relevant .ddl's into a Plugins folder in your project
thank you
do you know which dll's i need to copy?
is it just all mongo db dll's?
presumably you are installing via nuget so any dll's downloaded by that
What is this? If this is NuGet, Unity doesn't use it
You have to copy the DLLs into your Plugins folder manually
Or use the 3rd party NuGet for Unity package
do you know where i can find the correct dlls?
also found that the official dlls arent signed which apparently they need to be?
I don't do this often, and I'm on my phone. I get them from wherever NuGet usually downloads them from
Go to the NuGet page and click the download button, the dlls are in the package file which you can extract with any archiving software.
You also need to do the same for the dependencies, and the dependencies of the dependencies, etc.
(As a side note, are you using MongoDB driver to connect to a remote database on your server, or just a local one?)
yes im trying to get mongo db drivers to connect to mongo db database
do i just copy the files as they are and put into plugins folder in my assets?
A remote database?
yes
Just so you know, anyone can then look inside your game and grab your connection credentials, and then complete nuke your database, or modify their scores, whatever.
well for this project its fine
its just a school project
so this?
I don't think "it's a school project so going against the most basic security practices" is a good idea but eh, who am I to judge.
Yeah just find the dlls inside the package then drag them into Unity.
well i only have a few weeks to finish it and everyone including my teacher is using it and its what my teacher is teaching us to use for now
so yes, its fine for this specific project
well, when i copy-pasted the dlls into my plugins folder, i got loading errors
Ideally your server should expose just a few endpoints like "upload score" and whatever, then your Unity wouldn't even need this driver at all or all the code that's required to interact with the database, you just request the endpoint with UnityWebRequest and that's it.
Show the errors.
UnityWebRequest should be fine for this?
these errors
If your server exposes endpoints rather than like, literally the entire database, then yes you just need UWR to communicate and none of these stuffs.
Which dlls did you copy into Unity? I don't know which package you are trying to import but libraries support different runtimes (eg .NET Standard 2.0, .NET 8, etc), if you copy the ones that run on .NET 8 for example then they wouldn't run in Unity, because Unity isn't .NET 8.
thinking about it, i think i do still need the dlls as i need access to the database
You do not if the server exposes endpoints, and the endpoints are the ones dealing with the database, so your Unity game is only talking to the endpoints.
these are inside my plugins folder
Which folder is that coming from?
i dont know enough about servers to be able to argue about what i need
i just need access to my database, thats as much as i know
plugins folder in my assets
No, I mean which folder in the NuGet package.
those are the ones i copy-pasted from what was downloaded from nuget
sorry for the bad answers
Yes, and once you extract the package it should support multiple runtimes, each with its own folder of dlls. Which one did you copy?
i just copy-pasted all mongo dlls i could find from everything that was downloaded
Yeah that's not how it works, you can't mix all the dlls from different runtimes together.
I think it's better for you to just use NuGet for Unity instead of trying to do it manually.
youre not talking about nuget manager inside visual studio right now, are you?
NuGet for Unity is a completely different thing.
ok, ill look for it
Couldn't get it working no. Which screen space should camera be? there is overlay, and a few others.
so i got nuget for unity
do you know what version i need? im using unity 2022
I don't know, you have to figure it out yourself.
Hi folks, I don't know if this might belong to #💻┃code-beginner or here, but I'm currently facing some transform issues that I still can't resolve after 14 Google searches.
I have the given GameObject "point" where the red and green line meet and would like to move it 90 degrees to the right. As of now, I have adjusted the rotation of the GameObject to face the white cube. Now if I add transform.right to it's position to move it, I expect the yellow dotted line, yet I receive the point given below that. Both Vector3.right and transform.right bear the same result, which irritates me. Is there any way I can move my object via transform to it's right (and left) side it is facing, considering the x- AND z-axis from any given point?
sounds like the object is tilted over to the side
There are many rotations that face the white cube.
Quaternion.LookRotation takes a second argument that defines "up"; it's Vector3.up by default
oh, I see: it's moving in the +X direction, not -Y
i thought it was going down
that just means the object isn't rotated at all. Select the game object and look at the direction its handles point.
Make sure that you're in local, not global, mode here
I could use some help please.
While using a State Machine Pattern, my character keeps changing from the Jump State to Idle, and I'm not sure why.
Perhaps the execution order is the problem here.
If you update isGrounded after checking for a state transition, you'll instantly snap back to idle
but if my character is up in the air without colliding with anything, does the execution matter?
hmm let me see if I can give more info, one sec
Is your problem that you immediately go back to the idle state when you jump?
yea
well, no
it's more like as i'm falling
I'm gonna record, and share it
while recording, I watched the video back in slow mode, it's actually as you said, it is snapping back to idle immediately
I didn't realize it
Damn, ty @heady iris, oh my god I spent literally hours on this small error
(:
you'll need to enforce an ordering here
one option is to adjust script execution order in the project settings
the other is to replace Update/FixedUpdate/etc. with explicit method calls
My game has Entities with Modules attached to them. Only Entity has Update/FixedUpdate/etc.
It calls methods on the modules in those methods
Wondering if there is a great tutorial out there for multiple ammo type management. 5 weapons to start with different ammo types.
Pistol
SMG
Shotgun
AR
Grenades
@heady iris my fix
lol, idk if this was ideal, but it's what I could think of after torchering my brain for hours on this
I just didn't want to touch the script execution in project settings, and I'm not sure of what explicit method calls means xD
to start with NEVER check a float value for equality
how come
because of float inaccuracies
oh, even though I put the ">=" comparison?
I was looking at the == 0
oh, that's just checking if I'm standing still or moving
yes and it probably will never be EXACTLY zero, just the way float works
so I should always just have it change state to the walkState
I was just thinking if I was running into a wall, my velocity would be zero'd out
for X
no, you check check a range. instead of ==0 do >= -0.01 && <= 0.01. For example
or you can use Mathf.Approximately
yes
ty Steve and Fen
I appreciate you guys, my game feels so much smoother now
now I'm just gonna watch a handful of videos about coyote jumping
That's the fun part, because I am sure I am rotating this GameObject enough.
This is a Coroutine I have written for the positioning:
{
Vector3 startPoint = positionObj.transform.position;
int angle = 0;
while (true)
{
// Rotate like crazy
positionObj.transform.Rotate(Vector3.up, angle);
positionObj.transform.Rotate(Vector3.right, angle);
positionObj.transform.Rotate(Vector3.forward, angle);
// Move object now with changed rotation
positionObj.transform.position = startPoint + transform.right;
yield return Timing.WaitForSeconds(2f);
positionObj.transform.position = startPoint; // Return to start point, but keep rotation
yield return Timing.WaitForSeconds(2f);
angle += 30;
if (angle > 360) angle = 0;
}
}```
The object gets rotated, I am using transform.right to move it and put it back in it's original place 2 seconds later. It always lands on the same point, no matter the rotation. Do you have a suggestion?
oh, you're using transform.right, not positionObj.transform.rotation
what are you expecting it to do, you set the position, that is the position it goes to
@knotty sun This is what I initially asked. I can't find a way to properly move something exactly left/right of something, regardless of direction towards x- and z-axis.
looking at your code, you want the object to step out and then step back continually in a circle, correct?
Yup, this test code was supposed to do that. I tried with Vector3.right as well, with the same results. When I am transforming to the right, it should consider the direction it is facing every single time, and make a move to another spot.
indeed, the code as written should do that
let me just run a quick test, back in 5
what is your problem, be patient
i think he was pretty chill, what do you need help with
you are the one being rude and acting entitled
Ah chief I think I remember that problem, did you set up IntelliSense in VSCode?
lol wait check this out
https://www.youtube.com/watch?v=ihVAKiJdd40
In this video I'll show you how to quickly set up Visual Studio Code (VSCode) with Unity and Intellisense working properly 2022.
I also recommend disabling Telemetry in Visual Studio Code
if you do not want to send usage analytic data to VS Code:
File/Preferences/Settings (macOS: Code/Preferences/Settings), search for telemetry, and set the T...
This might be it
np
This one is way outdated.
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
what's the difference between Raw Image and Image? I'm aware in general you only need Image, which uses a Sprite where Raw Image uses Texture. A package I'm using is using Raw image and trying to understand a bit better what the reasons are 🙂
!ban 1119185460930039848 Homophobia in pronouns.
ohmohctp was banned.
try this
public class TestCircle : MonoBehaviour
{
void Start()
{
StartCoroutine(AdjustRightTransform());
}
private IEnumerator AdjustRightTransform()
{
Vector3 startPoint = transform.position;
float angle = 10f;
while (true)
{
transform.Rotate(Vector3.up, angle);
transform.position = startPoint + transform.right;
yield return new WaitForSecondsRealtime(.5f);
transform.position = startPoint; // Return to start point, but keep rotation
yield return new WaitForSecondsRealtime(.5f);
}
}
}
how many can make this.
seven
Interesting. I have created the class and in the other class where I initially generated the GameObject, I used AddComponent<TestCircle>(); and it seems to work!
But I don't really get the difference between the two versions, I am referencing the GameObject directly with positionObj and rotate/move it. With your script, it now directly accesses the transform and it works.
Thank you very much @knotty sun
the problem was twofold.
You extra rotations were screwing up the transform.right
Adding to angle every itteration was making it rotate too far every itteration (Rotate is cumulative)
It was just for testing purposes, before that, I applied rotation only once, and it still remained the position. I was just getting desperate and tried to get that damn point to move somewhere else
well, you have your solution, good luck
how come you sure about seven.
I counted
new studies suggest the number is actually 6.5
I honestly cannot see why anyone with any experience would consider that difficult and 2 days to make it?
why dont you try it.
it's really not that difficult
I have proc gen room solutions a damn sight more complicated than a simple resizable door
its looks simple. try it. its simple.
yeah actually looks pretty difficult actually, idk how to do it
do you have any video of it. let me try.
not a chance, that's business
i am a hardcore programmer cmon let me see.
Ninja, congrats on your accomplishment, but don't go challenging everyone to do something just because you feel proud of yourself.
the video is probably using an asset. Its not that diffcult anyway, there are tools that let you resize mesh without stretch
even probuilder lets you do runtime stuff like that with meshes
as long as all the parts are separate mesh/gameobjects too
wait those parts are separate meshes? that makes things much simpler
i thought it was like sprite 9 slicing but for a texture
That's one way to do it, then change the door knob position to 50% of the doors height, or however high you want it
Don't promote your content outside of #1180170818983051344
you don't even need a mesh, there are so many ways of achieving that technique
yeah many ways to accomplish the same thing
why dont you all try whatever ways you know. i would love to see. but i did complete programming out there no assets.
yeah but, for what reason should I take the time to do this ? I have no use for it
probably learn.
are you here for any reason other than to try to advertise the fact you can generate a door
i want to see that programming where you never achieved it.
ehh its a waste of time or me, I got a lot more complexities than a door going on. Dealing with Netcode
i'm busy
I have some draggable objects that can be dragged with mouse or using keyboard (to allow accesibility).
This is the keyboard and mouse endDrag functions
public void EndKeyboardDrag()
{
itemBeingDragged = null;
isDragging = false;
canvasGroup.blocksRaycasts = true;
PointerEventData pointerEventData = new PointerEventData(EventSystem.current);
ExecuteEvents.ExecuteHierarchy<IDropHandler>(gameObject, pointerEventData, ExecuteEvents.dropHandler);
if (transform.parent == startParent)
{
transform.position = startPosition;
}
}
public void OnEndDrag(PointerEventData eventData)
{
itemBeingDragged = null;
canvasGroup.blocksRaycasts = true;
if (transform.parent == startParent)
{
transform.position = startPosition;
}
}
This draggable object have to go to a specific zone or object that has this component:
public class DropZone : MonoBehaviour, IDropHandler
{
public TextMeshProUGUI phraseText;
public string correctWord;
private string initialText;
private void Start()
{
initialText = phraseText.text;
}
public void OnDrop(PointerEventData eventData)
{
if (Draggable.itemBeingDragged != null)
{
var draggedItem = Draggable.itemBeingDragged;
var droppedWord = draggedItem.GetComponentInChildren<TextMeshProUGUI>().text;
if (droppedWord == correctWord)
{
phraseText.text = initialText.Replace("___", correctWord);
Destroy(draggedItem);
}
else
{
Destroy(draggedItem);
}
}
}
}
For mouse is working but not for keyboard (I supose I'm emulating wrong the drop action). This are the full classes if you need to check something else: https://hatebin.com/fhzgvbaceu
so, I've recently started a project and I needed a procedural terrain generation, so I followed the tutorial of Brackeys on this subject but the terrain is not creating if the UpdateMesh() isn't called in a void update method, but it's taking a lot of resources for nothing. Do anyone know why it doesn't render the triangles ? here's the code : https://hatebin.com/umyfdqqmgt
What if you assign the mesh after calling UpdateMesh?
I'd expect this to work fine
but maybe the mesh filter doesn't respond to the change happening right after the assignment?
I tried moving it but no, it isn't rendering the triangles
Are you changing Xsize and Ysize somewhere else, maybe?
nope but I just got an error : IndexOutOfRangeExeption at line 54
it randomly worked without me doing anything, thanks.
is possible to change hdrp settings at runtime? i like to give player option to use raytracing, dlss and etc
hey yall, it's my first time making a custom inspector for a script and I think I made some sort of rookie mistake here.
While all fields drawn are editable, only the Y Rotation Limit fields and Y Position Limit fields retain their values. Everything else resets to 0 when clicking off or hitting enter after inputting some value. As far as I can tell, all 6 of these are identical so I don't know what's causing it. (Don't mind how X Rotation Limit has different display, i was fiddling with a better organized field)
#↕️┃editor-extensions and !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I don't know why I am getting this error all of a sudden
There are 3 event systems in the scene. Please ensure there is always exactly one event system in the scene
UnityEngine.EventSystems.EventSystem:Update () (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:543)
Solved really can't make a UI a prefab without this error?
guys who can help me with pacman
this is a code channel
yes and i'm developing pacman with unity
then ask a question if you need help with something specific
this is my enemyscript aka for the ghost. the enemy is getting stuck in the walls i dont know how to fix it. "using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemyscript : MonoBehaviour
{
public Transform player;
public float speed = 5.0f;
public float detectionRange = 0.5f;
private Rigidbody2D rb;
private Vector2 currentDirection;
private Vector2 lastDirection;
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.freezeRotation = true;
currentDirection = (player.position - transform.position).normalized;
lastDirection = currentDirection;
}
void Update()
{
FollowPlayer();
}
void FollowPlayer()
{
Vector2 directionToPlayer = (player.position - transform.position).normalized;
if (!WallInFront(directionToPlayer))
{
currentDirection = directionToPlayer;
}
else
{
AvoidObstacle();
}
Move(currentDirection);
}
void Move(Vector2 direction)
{
rb.MovePosition(rb.position + direction * speed * Time.deltaTime);
}
bool WallInFront(Vector2 direction)
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, detectionRange, LayerMask.GetMask("Wall"));
return hit.collider != null;
}
void AvoidObstacle()
{
Vector2[] directions = { Vector2.up, Vector2.down, Vector2.left, Vector2.right };
foreach (Vector2 dir in directions)
{
if (dir != -lastDirection && !WallInFront(dir))
{
currentDirection = dir;
lastDirection = currentDirection;
break;
}
}
}
}
"
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
my bad
no
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
can i send videos here?
you can do but before you do that your Move method should be called from FixedUpdate not Update
It updates after Update that is when physics are calculated
that is incorrect
FixedUpdate happens before Update on physics frames. and is called at a fixed rate, not every frame
i can fix the speed but that's not really the problem, it just goes up and down
i would recommend looking into a pathfinding algorithm like A* rather than what you are doing, your current method of pathing to the player is not going to be very accurate
thanks why everyone explains it that way I don;t know then your explanationsmakes sense though
I still have that Multiple Event Systems problem not sure why though? Not like I have multiple Canvases just one not creating any events in code for any reason.
having one canvas does not automatically mean you only have one EventSystem in the scene. if you have an EventSystem in your UI prefabs like you previously implied, or have them on DDOL objects, then you are likely accumulating multiple in your scene(s)
also the only time an event system is automatically added to a scene by unity is during edit time when you first create a UI object in your scene. if one exists in the scene already it will not create another. so whatever is causing the issue is something you have done incorrectly
Well Unity seems to be just creating them out of nowhere now after trying to create UI prefab it's up to 5 now noting has changed every time I hit Play it's creating a new one.
It strted at 2 and keeps going up
well you've not shown any of your code, or your setup or anything like that. so we can only assume you are doing something wrong
Yeah I am just thinking about starting a new Project adn say screw it and like i said no code is creating it I would have to post 4000 line here
So isn't there any other simpler way other than A* ?
I don;t know why its happening all I did was try to create aprefab Canvas and it started doing it
2d navmesh
but its just a* , anyway
that's still a*
bro im cooked
yeah you just don't have to write nodes, or any of that
appreciate the help guys
imo still good to learn how a* works and write it yourself
there are simpler ways to make an object move towards another object, however you want to move around obstacles and likely in a predictable way considering you are cloning a well known game so you should learn how to use proper pathfinding. you don't need to write all the pathfinding yourself, you can use NavMeshPlus which provides 2d support for unity's built in A* implementation (NavMesh). or there's aron granberg's A* pathfinding project on the asset store which has a free version. but the algorithm is actually fairly simple to learn and implement yourself
navmesh might give you wonky behavior because of local RVO avoidance (agents avoiding eachother) you might not need it
such narrow halls agents might go strange
indeed the A* pathfinding project is pretty good too, and might give you more options for fixing avoidance issues
my IDE keeps shooting this error to me. What caused this problem?
Puzzle game level editor, prevent user from sharing level before they have solved it themselves
At a guess you are using Editor code in a non Editor project
it doesn't even have RVO in the free version
Have you received an answer already?
I'm sorry, I meant the space of the Canvas, not camera.
For instance, this code assigs the anchoredPosition to the localPoint correctly, which means placing the RectTransform myRect in the middle of the screen mouse position, assuming
-
- The
Canvasis in eitherScreen Space - CameraorWorld Space
- The
-
- The correct
anchoresandpivotsare set formyRect
- The correct
Vector2 mousePos = Input.mousePosition;
RectTransformUtility.ScreenPointToLocalPointInRectangle(FindAnyObjectByType<Canvas>()
.GetComponent<RectTransform>(), mousePos, Camera.main, out Vector2 localPoint);
myRect.anchoredPosition = localPoint;
Note that if, for some reason, you have an irresistible desire to use Screen Space - Overlay, assigning the anchoredPosition directly to the mouse position in screen space aligns the RectTransform correctly, assuming the anchores are at min (0, 0) and max (1, 1)
If there is any case of you not liking your current pivots and anchores, the new position based on RectTransform.pivot, RectTransform.anchorMax and RectTransform.anchorMin may be calculated
||Though it's so troublesome, that in this case I would rather use the world position||
Need some advice guys... this coroutine I have here, shouldn't it run perpetually until the end of eternity?
It seems like it at some point stops running though.
unless you disable, destroy, object or mess with Time.timeScale
is Yielders a custom class?
You'll need to determine when it stops running to attempt to figure out why.
Yielders looks very suspect there unless an Exception is being thrown
As is, I'm going to assume you know how to implement coroutines and that the issue lies elsewhere - disabled component, inactive object, destroyed object, manually stopped coroutine, an error etc
I thought it was a const
never heard of it, I presume it is self implemented or smth
any reason why calling functions in a serialized event doesn't allow floats or vectors? Looks like I can only call it with a bool, string, or no args.
true , or I guess they could be doing
public static WaitForFixedUpdate WaitForFixedUpdate= new();
idk why you would tho
It makes sense if they have pre allocated, it saves on GC
oh yeah true, I just usually put it outside the loop
makes sense for optimizing though
or just read the workaround page linked at the bottom and in the sidebar
there's one gotcha: WaitForSecondsRealtime looks like it gets modified by the engine (rather than just being used to tell native code what to do)
public override bool keepWaiting
{
get
{
if (m_WaitUntilTime < 0f)
{
m_WaitUntilTime = Time.realtimeSinceStartup + waitTime;
}
bool flag = Time.realtimeSinceStartup < m_WaitUntilTime;
if (!flag)
{
Reset();
}
return flag;
}
}
notably
It's a CustomYieldInstruction, not a YieldInstruction
genuinely curious what OP is doing there then xD
it does look like it's just a pre-allocated yield instruction
i want to make the architecture of my sound manager in the following way: everything that can emmit a sound will raise an event (SO), and a SoundManager will basically subscribe to all sound emmitters. (a sound event will pass along the necessary info such as materials, etc).
to me this would be perfect because of its simplicity, but i am worried of having too many events.
is it an ok method, or can it be improved somehow?
SoundManager will basically subscribe to all sound emmitters.
Probably best to just have a single static event to avoid managing all of that.
What's the goal here though?
To reduce the number of AudioSources?
hi
just to not even think too much about sound when doing gameplay logic. just fire an event and im done. afterwards i can just code the sound manager and subscribe to all necessary events. so i would say the purpose would be simplicity and decoupling.
edit: the events would actually be explicit sound events, but rather generic ones, like: inventory opened, bow fired, arrow hit, item drag started etc.
since not just the sound manager will be interested in them.
but at a later date, when wanting to do sound, I can just find the events that need to emmit it and it would be quite simple
You still need to decide which sound to play and where to play it, right?
Basically - what does your approach give you that you can't get just by using:
https://docs.unity3d.com/ScriptReference/AudioSource.PlayClipAtPoint.html
yea thats a good point, i would probably have to send the worldspace coordinates for every single event, even if it doesnt really make sense in the context of the event
i would be using that to play the sound clip, but having a single place that manages sounds for me seems a bit cleaner, idk
i guess im just a bit worried about having too many events
But if all it's doing is passing through to a call to PlayClipAtPoint, why not just cut out the middleman?
but it wouldn't jsut be doing that, for example: let's say I fire an "OnInventoryOpened" event. besides the sound manager that would subscribe to it, maybe there's a screen space vfx that needs to be played, maybe the save system wants to subscribe to it to pause time etc etc
i would be killing two birds with one stone
How can I make object to be triggered by particle system
Would you though? Because now the sound manager needs to subscribe to an OnInventoryOpened event? That seems really weird for a SoundManager to know or care about
And now the SoundManager needs to know about every single event in the game pretty much
correct, would that be a big performance hit?
it's not a performance problem it's a code architecture problem
Event subscriptions do create GC so, I mean, depending on the number of these things and how ephemeral they are, it could be a performance problem
you've given me a lot to think about. thanks a lot for your help and thoughtfull answers
private void OnTriggerEnter2D(Collider2D collision) {
if (damageDone) { return; }
damageDone = true;
DamageAbsorber _da = collision.gameObject.GetComponent<DamageAbsorber>();
if (_da != null) {
print("damage absorber exists");
if (_da.owner != attack.owner) {
attack.Nullify();
Kill(true);
print("attack nullified");
return;
}
}
PlayCharacter _char = collision.gameObject.GetComponent<PlayCharacter>();
if (_char != null) {
if (_char == attack.owner) {
Kill();
return;
}
print("damage dealt");
_char.Hurt(attack.owner, attack.power.stats.knockback);
if (attack.hurtEffect != null) {
Instantiate(attack.hurtEffect, _char.bodyCenter.position, Quaternion.identity).Setup(attack.owner);
}
}
Kill();
}```
guys, im trying to make an object to nullify its effect and damage if the object it collides with contains a DamageAbsorber but for some reason it doesnt work atall or aways
what culd the problem be?
dealing damage works fine, but it like skips the damage absorbing part
lots of things.
- The GameObject doesn't have a DamageAbsorber
- this isn't true:
(_da.owner != attack.owner)
Debug.Log is your friend
well the object does contain damageabsorber component
how do you know
but damage absorber print doesnt print
Is print("damage absorber exists"); printing?
Then it doesn't
no
This might help you:
Debug.Log($"The object we hit was {collision.gameObject.name}");```
maybe it collides with character first, and then with the object that is supposed to nullify the damage
i see i will debug it now
Hence why we debug
are those separate objects?
yes
it just kills the damage object
Ok so
its irrelavent
no it's very relevant
Here's the thing
OnTriggerEnter can happen with multiple objects in the same frame
if you enter both objects in the same frame
i guess i have to get all the objects it collides with
yes it spawns directly over them
Yeah basically you could be hitting both at once, and then this code will run for both the player and the absorber
yeah but it has to run first for the damage absorber and then for the player
so it can nullify the damage
which one is to get all the objects it collides with
There isn't a super clean way to do that with OnTriggerEnter
A better approach may be to remove the collider entirely and just do Physics.OverlapCapsule in FixedUpdate
or do a Physics.CapsuleCastAll or similar
Because OnTriggerEnter gets called separately for each intersection
to do it in OnTriggerEnter you'd have to put them all in a list or something and then handle the rest in a coroutine in yield WaitForFixedUpdate
Because that runs after all the triggers according to https://docs.unity3d.com/Manual/ExecutionOrder.html
because it's possible for multiple physics iterations to run in a single frame
LateUpdate vs Update makes no difference here
You can't control whether physics runs multiple times in a frame
that happens if and when the framerate gets low
nope
because that happens before physics
though i mean I guess it could handle the ones from last physics update
it would just mean there's a potentially visible delay
so what i will do is populate a list with the collisions and in fixed update if the list count is higher then 0 then go through it
Really I feel like CapsuleCastAll in FixedUpdate would be a better solution overall though - plus it would eliminate the risk of tunneling
tunneling?
ok i guess that wuld be better
Not sure if this is the right place to ask, but where are these Job System settings saved? everytime I restart the editor they're being reset
Hey, I'm using cinemachine and in a 2D level when a player zooms in with the mouse the camera orthographic size changes and I also move the camera so that the mouse pos is the focus point (much like in google maps), but this causes it to jitter (https://gyazo.com/949970eaf700c1100b1c597bb568ce67). I update both the movement and zoom in the same fixed update and both are frame independent so I don't really know how to fix this.
Seperately they both look smooth but together it looks really bad and not sure how to handle that
Should probably post your code
So in the update the zoomvalue gets regularly updated together with the necessary movement that goes with the zoom (already updated the 'fixedDeltaTime' here to 'DeltaTime')
The override in there is just to keep track of the necesary movement of the camera that has to be done
Then in the fixed update the movement and zoom are actually being executed
updatecamerazoom is basically just applying the new orthographic size
and applytotransformation is basically just updating the pos
So you're lerping the zoom in update, but moving the camera in fixedupdate? Probably some confliction there, but I could only guess. There's obviously some sort of desync between the two operations.
yea, I tried moving it all in the fixedupdate first but then the inpout wasn't registered properly, but maybe I should just do the lerp in fixed, i'll give that a go
Just something I'd probably play around with is just using Movetowards over lerp perhaps
Ah, but it seems like you want to zoom little by little so lerp may be the better option
https://gyazo.com/fc90360c205e67ec32b39eb4e4975f2b made it feel a bit better but still bit off
yeah we smoothen it out
I think the lerp might be causing the jumps though now that you mentioned it
It's one of those situations where I just start swaping stuff around and see if that fixes it
ortho camera probably adds to the problem too
Tried the MoveTowards like you suggested and it gave me some other problems but the jitter is gone so now I do know where the problem is so that helps a lot already
I cant seem to find any working solutions, but im having an issue with touch input going through UI. I have tried various solutions from web searches and none I have come across have worked (most are years old so might not be relevant with recent unity versions). I have working mouse input blocked from going through UI, but cant seem to figure out how to do it with touch
@latent latch I think the main issue with the lerp is that if I use my scrollwheel multiple times while its lerping, the speed just changes abruptely from slowed down to speedy again while the movement is just trying to catch up. I'll play around further with it, thanks for the insights!
Probably want to clarify "going through UI" means
is it targeting something behind it but activating the element you clicked anyway
how do i fix this, when ever i try to go back and fix something it just overwrites the thing im trying to fix
I have some 3d objects behind a ui menu that pops up. When trying to click on ui elements in that menu, the touch inputs go through the ui and interact with the 3d objects
Two different raycasts
Physics.Raycast targets the scene elements, Graphics.Raycast affects the UI
Physics raycast wont be blocked by the UI
assuming this UI is an overlay
someone please help me with this
the ui is an overlay but i am also working with physics.raycast. I allow the player to select a tile with the physics.raycast, then this menu allowing them to edit the tile comes up, but any tiles behind that menu get hit by the raycast. In the tile selection script i specify physics raycast, is there a way to make the ui block it then?
Few ways, one being if you detect the mouse is over UI elements, don't cast the Physics raycast
i think you hit your Ins key on your keyboard
i got it fixed
Well i have it working with mouse simply using IsOverGameObject(), its touch input thats the problem, mouse is fine. That method doesnt work with touch, and some other solutions ive found semi work, they mess with camera movement though causing other issues
https://docs.unity3d.com/2018.1/Documentation/ScriptReference/EventSystems.EventSystem.IsPointerOverGameObject.html
This will detect if the UI raycast hits a UI element so
-> if hit UI element, don't physics raycast
Oh, huh wonder why it wouldnt work with touch
its a common issue that it doesnt work with touch from what ive seen, people have had to do scripting workarounds. Currently im using the IPointerClickHandler interface which does block touch raycast from going through, but then on keyboard the zooming of my camera doesnt work with the mouse wheel now
although i wont need keyboard/mouse input as im publishing to mobile, but i swap between testing on keyboard/mouse and mobile, but i guess i can just only test on mobile past this point
public class CanvasRaycaster : MonoBehaviour
{
GraphicRaycaster m_Raycaster;
PointerEventData m_PointerEventData;
EventSystem m_EventSystem;
void Start()
{
//Fetch the Raycaster from the GameObject (the Canvas)
m_Raycaster = GetComponent<GraphicRaycaster>();
//Fetch the Event System from the Scene
m_EventSystem = GetComponent<EventSystem>();
}
public bool IsPointerOverCanvas()
{
//Set up the new Pointer Event
m_PointerEventData = new PointerEventData(m_EventSystem);
//Set the Pointer Event Position to that of the mouse position
m_PointerEventData.position = Input.mousePosition;
//Create a list of Raycast Results
List<RaycastResult> results = new List<RaycastResult>();
//Raycast using the Graphics Raycaster and mouse click position
m_Raycaster.Raycast(m_PointerEventData, results);
//For every result returned, output the name of the GameObject on the Canvas hit by the Ray
if (results.Count > 0)
{
return true;
}
return false;
}
}
This is something I've found from the forums before which is better for the new input module
But instead of mousePosition it would be current pointer input
ill try this out, its similar to some things i saw but a bit different so might work
Another way is is if you can get the vector2 screen coordinates and compare it to UI elements
but if IPointerHandler works then just go with that
so i did try this out as a heads up, in my case it may not be viable as even inactive ui objects seem to be counted in the raycasts, which just seems odd to me, so to get this to work id have to calculate the position of the touch and know how many ui elements are there (active or inactive) and adjust the count off that.
I'd just go with the IPointerHandler solution, because the next thing I'd suggest is using RectTransformUtility and checking each rect if point is located in it
Inactive stuff being counted in the raycast does sound like an error somewhere though
i just read that if the raycast target box is checked on an element its counted even if inactive
if anybody is interested i figured it out. So tons of "touches" can happen within a single update frame and for some reason it looks like one or two of them get registered as a Input.GetMouseButtonDown(0) rather than a touch (didnt even have my hand on my mouse so unsure of why this happens) but this resulted in some of the "touches" branching to my mouse input code (which still has the !IsPointerOverGameObject(), but doesnt work for some reason when it works for actual mouse input). Solution was to only branch to my mouse input code when there are 0 touch counts. So IsPointerOverGameObject does work for touches, but just seems to have a flaw if a touch is registered as mouse input, idk its all odd to me
Hey guys I'm wondering if I encountered a bug...
I'm reading the value from Event.current.mousePosition, and the documentation claims it is in ScreenSpace, but that's not what I'm getting. The correct conversion I found is this.
Vector3 ScreenSpaceMP = new Vector3(Event.current.mousePosition.x, ccam.scaledPixelHeight/2 - Event.current.mousePosition.y, 0) * 2;
I'm on macOS unity ver 2022.09, is this a bug or inteded behavior?
How off are the values?
Does the top left yield a zero vector and bottom right yield your screen width/height in value?
The top-left of the window returns (0, 0). The bottom-right returns (Screen.width, Screen.height).
Working on creating a loading scene. Have a scene that displays loading messages. Also have a Loader type class that is meant to initialize the next scene which is async loaded when the loading scene is started. This Loader instance is flagged as do not destroy. I need help figuring out how this Loader instance can create game objects in the newly loaded scene. The async operation is flagged allow scene activation false so I can wait for the game objects to be loaded. Insight would be appreciated!
When the async operations progress is >0.9f, set the allow scene activation flag to true yourself, and the scene will be loaded. You can subscribe to SceneManager.sceneLoaded, or, on your scene load async operations completed event to spawn objects. If you have multiple scenes, then you might have to set the active scene to the newly loaded scene so that the spawned gameobjects actually spawn in the new one using SceneManager.SetActiveScene
ya that last part would defeat the loading screen purpose, I want to do something like a constantly updating text object that is telling the player what is loading, so naturally it made sense to me load the next scene and related game obejcts asyncly. however, I just don't really konw how to notify the load screen scene of what is being created on the new scene
okay guys can someone please help me (urgent) I'm doing a 2d platformer rn, and everything works fine, except that when I build the game the jumping and shooting doesn't work in 1 scene. the only difference in that scene is that the camera is different, and everything works fine in the editor, but in the build the jump doesn't work and my bullets go in a weird direction. does anyone know what might be up with it?
code or no dice
idk which script it would be though, cause like I said everything works well in every other scene and even the bad scene works perfect in the editor
I think the tags might not be loading properly in that scene, but idk how I would fix that
First things
Unity version?
Build Platform?
Development build?
Did you look at the player logs?
Error logs, something-not-assigned, unassigned tags, unassigned layers, misnamed game objects that mess up code when GameObject.Find(hardcoded_value) is used
Lots of possible wrenches thrown in
Perhaps you forgot to add a component
Try copying the element from one scene and pasting it into the other scene and see if it still breaks
2022.3.4f1
windows
no
yeah, still couldn't figure it out
it's just confusing cause it only happens with the 1 scene, and only in the build
that is why you make a development build and then look in the player logs for information
also sorry if I'm hard to work with rn, I've been on this project non-stop for the past 18 hours getting it ready for a showcase that I leave for in an hour
ah okay, I'll check that out
also, btw 2022.3.4 is not a good version to use. You may find upgrading to the latest 2022.3 LTS will solve the problem
alr thanks, I'll see if that helps
also yeah there's a bunch of errors in the dev build
ok, so now you know where to look
yeah, thanks
I'll try the new version of unity, cause rn the only error I'm getting is that it's not getting the movement script off the player, even though it works fine in-engine
that may be a code execution order problem, quite common in builds
any fix?
yes, check that you are using Awake and Start correctly. You can also hard code the execution order of scripts
okay I got one of the two issues solved
I was finding an object using a tag, even though the object I was finding was it's parent, so I messed up there lol
somewhat odd then that it worked in the Editor
yeah idk, it worked fine in the editor, but not the build, but obviously using GetComponentInParent is better
and just as I thought the other issue was also easily solved by replacing the FindObjectWithTag to something better
thank you sm SteveSmith, you really saved me (this project is a final grade)
you're welcome. Best of luck
Does anyone know how to get the equivalent of "GetKeyDown" with the newer input system?
I'm trying to detect when a key is pressed and then move the player to the opposing side of a door/airlock, however, if I just detect when the key is pressed it will move the player back between the two points until the key is released.
I've tried searching for a solution but can't seem to find one, and this little problem is causing way more grief than it should.
show how you are currently checking for key presses
public void OnPlayerInteract(InputValue value)
{
PlayerInteractInput(value.isPressed);
}
public void PlayerInteractInput(bool newPlayerInteractState)
{
_playerInteract = newPlayerInteractState;
}
Where _playerInteract is a boolean value.
ah you're using the SendMessage option on the PlayerInput component. gimme a sec to see if there's any way to do what you are trying using that
Thanks.
you'll likely need to change the settings on your actual input action for this behavior
probably better to use isStarted rather than isPressed
InputValue does not have an isStarted property
the best option would be to use a different behavior on the PlayerInput component
even if they use the Invoke Unity Events option they'd get the full callback context. with SendMessage they get this super barebones data
does it not, I thoght the process was Started -> { Pressed } -> Cancelled
this is why I implemented my own code to use the new input system
InputAction has what you say Steve:
Hey, any idea why my scroll rect is not correctly masking its content?
which is what I use
What behaviour would I need to use?
use either Invoke C# Events or Invoke Unity Events for maximum customization (when using the PlayerInput component)
Will I still be able to use isPressed for other inputs?
you'll get the full InputValue.CallbackContext
Cool. I'll see if it works.
https://gdl.space/rehuzanaqo.cpp
Trying to get my laser bullets to fire in the direction they are facing along the Z. For some reason despite my code being right, no velocity is ever gained. I've tried velocity and adding forces but they are always static
transform.forward points along the Z axis which is used for depth in 2d. you want either transform.right or transform.up depending on the direction the object points when not rotated
also Rigidbody2D's velocity is a Vector2 so there is no Z axis on it anyway
Would you recommend Invoke Unity Events or C# Events?
i personally don't even recommend using the PlayerInput component. I prefer to generate a c# class for my action map and instantiate that and subscribe to the regular c# events on that instance.
but it makes little difference what you actually choose between the two, the deciding factor would be whether you want to subscribe to the events in the inspector or not. if you do then you have to use the Unity Events option
hello guys, I have a HDRP environment and when I add any object to it, the object become very shiny is there anything that I can do other than changing the object material to HDRP/unlit ?
this is a code channel
From my understanding, using the C# events method means you don't need the player inputs component on an object. Is this correct?
that's only true if you generate the c# class and create an instance of that. if you are using the PlayerInput component with the Invoke C# Events behavior then you obviously still need to use the PlayerInput component
Yes, that's what I was referring to. Thanks for confirming.
Also, will the generated C# class update whenever a new action is added to the inputaction asset?
when you save the asset it will regenerate the class
Perfect.
Thanks again, hopefully this fixes the problem!
Has it been confirmed is setting enabled.false is faster than a guard clause in Update ?
ie. what is the overhead of Update vs the overhead of setting enabled
disabling it does more than just prevent Update. i imagine there is very little, if any, actual difference in the performance
I usually just poll a flag and return early if I don't have a render ;)
yo! i got a tiny problem that's been holding me for quite a while... well, I need a formula that changes Orthographic size relative to resolution based on a default Orthographic size and lets assume that the Default Resolution is 1920x1080 and the default Orthographic size is 500, and the resolution was changed to 1366x768 in that case what would the orthographic size even become? how do I calculate it and does the same formula apply to 2560x1440 res?
Orthographic size is half of the vertical size of the camera sensor in world units
(or was it just the vertical size? it's one of those two)
okay, yeah, it's half of the vertical size
so an ortho size of 10 means that the screen is 20 meters tall
uhh soo 1366 / 2 * 500 / (some ratio?)
ortho stuff confuses me but looks so nice
20 units, actually, since a unit isn't necessarily a meter
For orthographic size of 500, you'll have problems making that pixel perfect for any monitor resolution
Since no monitor resolution evenly divides by 500
that's the default assumption (and it's what the physics system is using!)
Default for 3D, but in 2D it's a lot more variable 🙂
gravity is still -9.81 by default
you can certainly violate the assumption, of course (:
Though if you're deadset on 500, grab the pixel perfect camera from the 2D Pixel Perfect package in package manager, as that can also set up the black borders to keep things pixel perfect no matter what resolution you go for
use the pixel perfect camera if you're using pixel art that needs alignment, yeah
Ideally you pick a resolution that fits most of your target monitor resolutions.
Like Celeste is 320x180, because that easily divides into 720p and 1080p, and anythiing that is a multiple of 1080p
Anything where the vertical game resolution can cleanly divide 1080 is good for most
Mine is 384x216, as 5x 216 = 1080
So orthographic size for that is 216 / 2 / PixelsPerUnit
if someone plays my game on a 1440p monitor, it will end up using 1296px vertically, with 72px on top and bottom being a border
Unless they turn off pixel perfect, then it will stretch but no longer be pixel perfect
hmm correct, but my Canvas is World Space, and Im not Exactly Deadset on 500, I could go for something else, as long as it works really...
so I can Just Change the Default... though I'm not sure to what... or what formula to use with it
What game resolution do you want?
well everything was set on 1920x1080 on default
Yeah, but are you making a 2D sprite game?
I tried a few different formulas but some which worked on 1366x768 didnt work on 2560x1440 and vice versa
well yea
You'll need to decide on a monitor resolution to support, like 1080, and find a game resolution that evenly divides into that, before we can find an ortho size for it
You won't find one that fits every monitor res
the ohters will just need to make due with black bordering
or stretching
oh, yeah well since the Canvases are all world space, the Background (black) ends up being the border...
so aslong as the whole vertical side of the canvas is in screen it should basically work
@native steeple
Orthographic Size = Vertical Game Resolution / 2 / Pixels per Unit
That's the formula
My game is 384x216, and my PPU is 8 for all my assets, so my orthographic size is 216/2/8 = 13.5
This only works if all your 2D assets use the same PPU
Anything with a different PPU might appear stretched or scaled oddly
well I have all my 2D assets at 100PPU... so this should work? I'll try it rq and give ya feadback of What happens
Basically the camera is figuring out how many units of stuff to draw from the center point to one of the vertical boundaries.
So if the orthographic size is 8, then it will draw 8 units of stuff from bottom border to center, then another 8 units of stuff from center to top border
If PPU is 100, then it draws 100 pixels per unit, so you end up with 1600px from top to bottom.
That's all the formula is doing
hmmm nope no luck, infact I cant Even see the Canvas
can you screenshot your camera settings in the inspector?
heres my code + the ss
nope, its world space
Ahhh, those are tricky, since the camera might be too close to it or past it
If your game is entirely 2D you probably should use overlay, unless you have some special csae?
well, the camera is static, it doesnt move, and neither does the canvas, and yes I Wanted to do that But I Need world space because I am Renderring 3D Objects, Which Have 2D Objects All around so it wouldnt work any other way
3d objects in the canvas? There's a workaround for that
What you can do is set up your 3D objects somewhere in the scene that the main camera cannot see them. Setup a new camera that is only looking at those 3D objects, and then renders to a render texture. Then in your canvas have a rawimage that references that render texture. Voila, 3D stuff in your canvas
the problem isnt with the 3D Objects, Its with the 2D Objects That Have To warp around them... In this case its a ring, which should also be able to rotate, so I thought This is the Best Approach
ohhhh
Does this have to be in the canvas, or can it just be in the world scene itself?
the player is already being renderred in a different camera
nope, Unfortunately it has to be in the Canvas
Its part of the UI? like clickable?
can somebody help me achieve procedural walk animation like in unity example
-i just added a maximo model , and replicated this sample robot and here iam
yup, and also the ring is UI + Face expressions and stuff
Might be able to mimic it being part of the UI through OnMouseEnter/Exit/etc. methods on the objects, and giving them collisions.
I've done that in the past and faked them being buttons
oh... though I'm Kinda Over this as it would take forever to redo now... So I just Plan On seeing what I can Do with Orthographic size... in any case I do Think I have a solution, and its to shrink the canvas to the Screen size and it should Be as simple as
camHeight = _mainCamera.orthographicSize * 2;
float scale = (camHeight / Screen.width);
transform.localScale = new Vector3(scale, scale, scale);
It Should Theoretically work... though I Still Wanna Learn How to Deal With Orthographic size... Cuz whats better than learning something new! (sorry If I'm troubling you with my Dull Curiousity...)
No trouble. I think if the camera can't see the world space UI then it must be positioned oddly to the camera, or the scale is wrong somehow.
Scale might be it, as the camera might be looking at it but nothing is drawing because its focused and zoomed in on an empty patch of it
I remember scaling of world space UI to be a massive pain, as the math results in ugly numbers
hmm Yeah Thats Probably the Case, thus I'll Try to Roughly Round up some Decimals to ease it
oh well in that case I'll scrap the Ortho Idea huh
thank you tho, I learned a few stuff still :D.
hello
The top left is 0,0 and the bottom right is Screen.wh / 2, it's exactly half of what it should be...
Game.Instance.partyManager.onCharacterAdded -= (character) => CreateCharacterCard(character);
Game.Instance.partyManager.onCharacterAdded += (character) => CreateCharacterCard(character);
Is there a way to do it correctly? I think that above code doesn't unsubscribe properly for me.
I can't do RemoveAll as other scripts might be needing those
You'd have to store the original lambda in a variable. Even though they are the same code there those are 2 completely different unrelated lambdas so the -= doesn't find a match.
this, or use a method instead of storing a reference to the lambda
How do I use a method in this case?
in fact, the signature of the event and the method you're calling in the lambda seem to match, so you could even do Game.Instance.partyManager.onCharacterAdded += CreateCharacterCard;
that works? 😮
yeah, references to methods can be assigned to delegates
Let me try, I thought that having an argument prevents it.
the delegate type and the signature of the method just have to match
Ah I see, so I might need to add argument to a function if its missing it(even if it doesnt need it)
I had another event which doesnt need character, so that is why I wrote it the way I did
yes, but usually it's nicer to declare a new event handler method that calls the method you want with the correct parameters, so you don't have to modify the real method
makes sense
I only use lambdas when the event signature doesn't match the method signature, and there's some extra information I know at runtime when subscribing to the event that is needed in the parameters for the method.
And then I'm careful to not ever need to unsub from it, or if I do then I have to create and store refs to the lambdas as I make them
Like if the event is just onClicked, but the method takes an integer index for which option was clicked, so I make a lambda that fills that in when iterating over all the buttons.
if I never need to unsub at runtime, great.
If I do, then I have to store those lambas in a list
Better and better for the prototype ^^
I have three Slider objects (S1, S2, S3) that contain SliderTicks script. At Start I am calling the getcomponent function (this.getComponent<Slider>();). Will compiler fetch the Slider component of their respective objects (e.g., S1 sliderTicks will fetch slider at S1) or is that random? As in, the getcomponent can fetch any of the slider component (S1, S2, S3)?
Look, I would suggest you to have a look at the ScriptableObjects if you don't know what that is yet.
When doing this kind of behavior, I would always recommend having as many classes as needed inheriting each other.
-
- Create a
ScriptableObject A, which contains the whole information for all your items like weapons, spells and type of damage etc. For example,cost
- Create a
public class ItemObject : ScriptableObject { }
-
- Create the
ScriptableObjectsB,C,Detc. for every type of your item. They all should contain the information specifically for the item. E.g.damagefor weapon,whateverfor spell etc.
- Create the
public class WeaponObject : ItemObject { }
public class SpellObject : ItemObject { }
public class DamageObject : ItemObject { }
This should make it easier for you to manage the different possible items for the game directly from the Inspector.
If you have any further questions, feel free to reply to this answer. I'll be able to answer when I have time.
Make sure you then create a list out of all those items and add them to your UI
items.ForEach(i => Instantiate(GetItem(i), itemHolder.transform));
The script will only grab the component on the object the script is attached to. So S1 object with SL1 slider will grab SL1 slider
Well, GetComponent<T>() gets the component on the object
Also no this reference required
Now if you have multiple components on the same object, the order is unspecified, so use the plural GetComponents method instead
Use this when dealing with the local variables with the same names as the global ones or constructors etc.
But, scriptableObject is usefull for my "stanza" (effect and cost compensation used for create a spell) ?
And if yes, i need to create a scriptableobjet for every "stanza" ?
And if yes again ahah, can i "merge" all scriptableObject for have my spell with all "stanza" ?
- Yes, sure, you should specify the variables like
float costCompensationin yourScriptableObjectif it's not the same for all the items - Depends on what you mean.
- No, the
ScriptableObjectas aclassshould be created just for the item branches like weapon, spell etc. - Yes, the
ScriptableObjectshould be created for every individual "stanza", which is not the same as the other one. E.g. has a difference name etc.
- No, the
- What?
So nested lists with the numbers are not available with the Discord's md
For exemple :
Here i have 2 stanza, one for have fire damage and one for cost compensation
And in the futur, i want add "create spell" for create the spell with all stanza
Here, if i create this spell, i have a spell with fire damage and use my mana
So in this exemple, i can use scriptableObject for all stanza ?
I mean. You surely can create the ScriptableObjects in the edit mode and on run time, if that's what you want. You just gotta make sure you know how to merge them
So as I have understood, you want to create a single spell from both e.g. "fire spell" and "water spell"
Honestly, just have a method, which casts a spell. In this case you simply call the method multiple times?
Ohh so i can use scriptableObject for every stanza and then, merge them in one scriptableObject "Spell"
You can, but it doesn't make any sense
Give me the example of the stanzas available
And how they gotta be merged
A scriptableobject can have a list of other scriptableobjects, as if it were a container, so that's one way to do it
Okay wait ^^
I don't think that's what they mean
Perhaps, it's like fire with earth and getting lava
The way I'm doing abilities (like spells) is with scriptableobjects per ability that use serialized classes for each feature or logic chunk they need, using this package
https://github.com/mackysoft/Unity-SerializeReferenceExtensions
Each serialized class holds the logic for doing something, or for checking a conditional, and the ability SO just has lists of them exposed in the inspector to tweak each one
So KAPHA is a spell, and you get KAPHA if the player combines Earth + Water (which are not spells on their own?)
I got no idea what kapha means, but I feel like that's what they want?
Also earth and water should exist as the spells on their own
Well, you posted a picture with KAPHA in it, so I have no more idea what it means than you do 😄
I know, I just got the first suitable picture from the web
So whatever kapha means, Steamox is surely gotta find it out!
mmm pitta
So :
Offensive Stanza (Spell) :
Fire damage
Cold Damage
Electricity damage
...
Offensive Stanza (Melee) :
Damage
Bleeding
Accurate
...
Compensation Stanza :
Mana
Health
Speed
...
Offensive :
Used for the damage or increase the accurate or DOT
Compensation :
Used for choose what we want spend to have a balance action
Exemple :
Melee stanza :
Offensive
Damage (cost : 5)
Bleeding (cost : 10)
Accurate (cost : 15)
(Total cost : 30)
Compensation
Mana 10 (cost : -15)
Health 10 (cost : -15)
(Total cost : 0) (Balanced)
Here , if i create this action, when i hit a enemy , i will hit with more damage, with bleeding and more accurate but i wil spend 10 health and 10 mana for each hit
longgg
There's a game pattern for this called meta magic. Basically just composition
Weapon contains a spell, that spell contains behaviour and source effect component
Yeah but i want allow to player to create his own action in game
new weapon(new component #1, new component #2)
all composition, and if you have multiple behaviours, you just do comparisons
(3D) Im trying to apply basic movement for character with rigidbody, on the one hand changing rb.velocity directly cancels the gravity, on the other hand using AddForce has accelration effect of a car and i dont want it, what is my alternatives?
So simply have a ScriptableObject for every stanza and add a new struct / class to the List of the merged stanzas. The mergedStanzas in your case are Offensive n Compensation, I suppose?
stanzas.Add(new(mergedStanzas));
||Also "example"||
rb.velocity = new Vector2(movementHorizontal * speed, rb.velocity.y)
you do know there are multiple ways to AddForce
So i pick up every stanza (that i created before in scriptableobject) in my window "spell creator", and add a button with "stanzas.Add(new(mergedStanzas));" ?
Yeah, need to merge offensive and compensation
ForceMode? i didn't find anything helpfull
not even VelocityChange ?
its still accelerating
no it is not, it a change of velocity from one speed to another
It's like you can make the player select the stanzas they see, and merge them using the Merge button
Also handle whatever behavior you need, when the particular stanzas cannot be merged or too many stanzas are selected etc.
Yeah that exactly what i want ^^
So the best thing to do in my case is to use ScriptableObject ?
Well, I haven't said anything about changing my opinion about using it, so yes.
Okay great thanks you so much for your help !
So use it for action for allow to player to use it (Like an attack) , i need to modify something or i can use the ScriptableObject like this ?
What does it mean?
Okay, I get it now. Yes, you'll have to manage the behavior the player has inside of the other scripts according to the selected ScriptableObject's variables
Yeah okay perfect thanks !
namespace Phone
{
using Player;
using UnityEngine;
public class PhoneAnimation : MonoBehaviour
{
public Transform phone;
public Transform camera;
public float rotationSpeed = 5.0f;
private Quaternion originalRotation;
private Quaternion targetRotation;
private bool isRotatingToPhone = false;
private bool isRotatingBack = false;
private float transitionProgress = 0.0f;
private bool toggled = false;
void Start()
{
targetRotation = Quaternion.LookRotation(phone.position - transform.position);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Q) && !isRotatingToPhone && !isRotatingBack)
{
toggle();
}
if (isRotatingToPhone)
{
camera.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
if (Quaternion.Angle(transform.rotation, targetRotation) < 0.1f)
{
isRotatingToPhone = false;
}
}
if (isRotatingBack)
{
camera.rotation = Quaternion.RotateTowards(transform.rotation, originalRotation, rotationSpeed * Time.deltaTime);
if (Quaternion.Angle(transform.rotation, originalRotation) < 0.1f)
{
isRotatingBack = false;
phone.gameObject.SetActive(false);
}
}
}
void toggle()
{
if (toggled)
{
PlayerController.instance.toggleMovement();
isRotatingBack = true;
toggled = false;
} else {
PlayerController.instance.toggleMovement();
phone.gameObject.SetActive(true);
originalRotation = camera.rotation;
isRotatingToPhone = true;
toggled = true;
}
}
}
}```
Does anyone know why whenever i press Q it just locks forward and doesnt let me unforward
anyone that could help me quick?
debug your flags
or better yet use visual studios debugging tool, also dont cross post
i see what u mean, how would u write then the movement script? i cant get it right
Donno about "quick", and that depends greatly on what it is you need help with, its usually better to just ask your question with relevant scripts, visuals and details, if someone happens to know about your issue maybe they can help, that could be in several mins or a bit later
flags?
yeasorry i asked in the beginner chat, thx for the quick respons anyways!
bools
you toggle but cant untoggle
something isn't unsetting, go debug the logic with statements or learn about connecting the debugger to unity and go through it step by step
thats not really the issue though, it just snaps straight in front of you, but the phone its suppost to rotate toward is above the player
Thank you!
I dont think I see anything wrong with the lookRotation or the RotateTowards
unless rotationspeed is being modified further, or something else is acting on the transform
LookRotation: PhoneAnimation to phone direction
rotateTowards: interpolates from the PhoneAnimation object towards the LookRotation at 5 angular units a second
Is this part
camera.rotation = Quaternion.RotateTowards(transform.rotation, ...
Shouldn't be like this?
camera.rotation = Quaternion.RotateTowards(camera.rotation, ...
does anyone know how to set the resolution of a game
In build or in editor?
Setting in build is funky for some OS so you would change it via code
WebGL build should be fine, but I know windows will default it to another res
both would be nice to know
for now just need to know for editor
im trying to make my game 4:3 but thats not an option
I thought it was Game window
ye but for me it dont show 4:3
is that just not an option
Isnt there like a add more option tgere
Could be some extra options elsewhere but I remember having a bunch of specifics for each type of phone
I fixed that and now it works properly in that sense
namespace Phone
{
using Player;
using UnityEngine;
public class PhoneAnimation : MonoBehaviour
{
public Transform phone;
public Transform camera;
public float rotationSpeed = 65.0f;
private Quaternion originalRotation;
private Quaternion targetRotation;
private bool isRotatingToPhone = false;
private bool isRotatingBack = false;
private float transitionProgress = 0.0f;
private bool toggled = false;
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Q) && !isRotatingToPhone && !isRotatingBack)
{
targetRotation = Quaternion.LookRotation(phone.position, camera.position);
toggle();
}
if (isRotatingToPhone)
{
camera.rotation = Quaternion.RotateTowards(camera.rotation, targetRotation, rotationSpeed * Time.deltaTime);
if (Quaternion.Angle(camera.rotation, targetRotation) < 0.1f)
{
print("Test");
isRotatingToPhone = false;
}
}
if (isRotatingBack)
{
camera.rotation = Quaternion.RotateTowards(camera.rotation, originalRotation, rotationSpeed * Time.deltaTime);
if (Quaternion.Angle(camera.rotation, originalRotation) < 0.1f)
{
print("Test");
isRotatingBack = false;
phone.gameObject.SetActive(false);
PlayerController.instance.toggleMovement();
}
}
}
void toggle()
{
if (toggled)
{
isRotatingBack = true;
toggled = false;
} else {
PlayerController.instance.toggleMovement();
phone.gameObject.SetActive(true);
originalRotation = camera.rotation;
isRotatingToPhone = true;
toggled = true;
}
}
}
}```
but it still wont rotate toward the phone, only in a seemingly random direction
if someone could pls tell me how to set the game to 4:3 in the editor that would b appreciated 🙏
And then add a new option in that dropdown, using aspect ratio
i knew that but i just realized im so blind
i didnt realize under that tab that at the very bottom, you can do custom ones
mb
right click ?
Hey guys, I am working on an existing project and I have a button that I can press. But how do I log the script from which that key press was called from? Also how could I see in which script Cursor.visible is set?
Depends what you need it for
I've this code snippet:
private void ExitTour(SelectEnterEventArgs _)
{
DelegatePortalCollision.OnPortalEntered -= ContinueTour;
foreach (GameObject tour in tourParents)
tour.SetActive(false);
playerTransform.position = resetPosition;
museumParent.SetActive(true);
currentTour = default;
DelegatePortalCollision.OnPortalEntered += StartTour;
}
And it triggers the collider that gets enabled in museumParent.SetActive(true);, even though before that collider gets enabled, the player position moves out of that collider playerTransform.position = resetPosition;. My leading theory is that it's due to the execution order, so it still receives the physics OnTriggerEnter even though I teleport it before - because in the order of operations in the backend it still actually teleports it after the physics check. Is this assumption correct?
The one you circled bellow is only relevant if you're using IK.
Assuming I understand the issue correctly, one possibility is that changing transform.position doesn't actually move the physical representation of the object untill the next fixed update. That being said, I'm not sure if collision events should be invoked if the objects already intersect when before being activated.
- You should not use transform.position with physical objects. Use rb.MovePositon or something similar instead.
Whee does this code run
And what components are on the player
Yeah I thought it might not be quite accurate, but it was my best guess
It runs on an empty gameobject
The setting is VR
So this'd be the player
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I thought it was alright to post it as the file since that gives syntax highlighting as well but sure ill throw it in a paste site rq
Here's how it looks on mobile
ah right
Didn't think of that, my bad
By the way, this is my current fix for it, which works with limited success
Is that the player object? Is it moved via rb or character controller? Are you mixing the 2? Where is the rb and collider?
A couroutine that waits for the next fixedupdate, turning off the collisions and then turning it on again after
It's the complete default way Unity gives it
Well, you'll need to figure out how it's being moved. As well as what exactly is colliding with your trigger.
Well it moves itself by means of charactercontroller
As well as what exactly is colliding with your trigger.
The player?
How do you know that?
Lemme make some scene screenshots rq to ppaint a picture
testing
What testing? Did you actually debug anything?
I don't see what calls ExitTour
oh wait nvm
ok IDK how the SRInteractable callbacks work
I.E. not sure where in the game loop that happens
Okay hang on I need to yeet some screenshots from le scene
exit gets called when you push that button at the right of the skeleton
It subscribes to that listener
I think you should start with debug logging things. It feels like there's a lot of assumptions you've built there without actually confirming any.
That grey cube, is to show the inactive collider
lol sorry, this game looks wild
It's for school, we're developing a project for a secondary school about biology
half a year project essentially
Eh fair, though I don't see how it could enact different behaviour than what I'm thinking of, but I should make sure
Esentially the problem is that if the player is standing where that grey cube is and then pushes the button, it'll instantly call the ontriggerenter in an exact order of execution that breaks it
(you can push buttons from a range)
By the by, this is the whole class that does the collision
using System;
using Tags;
using UnityEngine;
public class DelegatePortalCollision : MonoBehaviour
{
public static event Action OnPortalEntered;
private void OnTriggerEnter(Collider other)
{
if (!other.CompareTag(Tag.Player)) return;
OnPortalEntered();
}
}
It delegates it, that's all it does ¯_(ツ)_/¯
And checks for tag
Debug the colliding object in on trigger enter.
will do
yeah it's exactly what i expect
note it's after the if that that print is called
Okay, so the object does have a collider?
where that grey cube is, there's the collider
here it's inactive
here it's active
The player I mean
no the player has a charactercontroller
which has a collider build in
Hence I can
voidInteraction[0] = GameObject.FindGameObjectWithTag(Tag.Player).GetComponent<CharacterController>();
and then
private void ToggleMuseumPortalCollision(bool toggle) => Physics.IgnoreCollision(voidInteraction[0], voidInteraction[1], toggle);
You pass the CharacterController as the Collider
Note: the grey cube is purely a visual indicator for debugging*
It's so I can align myself to make the bug happen
Hmmm... I had the impression that character controller doesn't interact with triggers correctly.
Idunno, but it sure does here
So, if you really don't have an rb, you should be moving the object via the CC, not the transform.
Why? I purely just want to teleport the player outside of the collider range
Or should I do it through CC because that might potentially run before the collision check
therefore solving the problem
Into a default position in the main room*
Which right now is just a very fancy vector 1, 0, 1 so ¯_(ツ)_/¯
Physics and transform have both independent representation of their position in the world. When you move it via the transform, the actual physical position is only synced in the next fixed update. And we don't know how CC handles trigger/collider collisions, so it's hard to say what happens when you move it with transform.
You could try calling Physics.SyncTransforms after setting the transforms, but I'm not sure that would help
Lemme check
Nope
That approach does not work
Lets try moving the CC (through CC funcs)
I think I 'fixed' it
As far as I'm aware there's no like teleport function of the CC, and I can't really use force because that'd be inconsistent, and would still make it so that it'd start in the collider
player.enabled = false;
playerTransform.position = resetPosition;
player.enabled = true;
I just disable it, set transform, re-enable
player is the charactercontroller btw
also yes there's redundancy rn, I know, I need to clean it
yeah that's how you're supposed to teleport a CC
https://unity.huh.how/character-controller/teleportation
ah
I tend to like never work with CC's, since this is like the first time I use VR
And I like using RB's for my normal games
Yeah, to be honest, CC is junky af.
^
KinematicCharacterController >>>
I'm not going to touch the template controller that unity gives me for vr more than I have to
Thanks for the help btw @cosmic rain !
cc can be good but takes too much customizing for that
Can someone help me with something localization related?
public static List<string> getTextBank (string key, string box) {
#if UNITY_EDITOR
AssetTableCollection collection = LocalizationEditorSettings.GetAssetTableCollection("Text_Languages"); //This detects the table entries
var table = collection.GetTable("en") as UnityEngine.Localization.Tables.AssetTable;
int foundEntries = 0;
foreach(var v in table)
{
foundEntries++;
}
Debug.LogError($"We found {foundEntries}");
#endif
TextAsset localizedTextAsset = LocalizationSettings.AssetDatabase.GetLocalizedAsset<TextAsset>("Text_Languages", key); //The keys to the table entry
if(localizedTextAsset == null) Debug.LogError($"Oh no, we can't find {key}");
No matter what I do, trying to get the correct key text to a localized asset table entry just keeps returning null.
Does anyone know how I would go about making a Planar graph for use as a dungeon-esque thing like this?
Do you need a planar graph? Can it be an undirected graph?
I am fine with it being undirected
I just want it to look similar to the image above
Cool. What’s the workflow here? Are you trying to procedurally generate something like the above image based on a given graph of nodes? Like what is your source data and what are you trying to do with it. I feel like your problem is a bit vague still so it may be hard to get help here without more specifics.
I’m trying to completely randomly generate the nodes. The problem is I don’t know how to go about making it.
Guys i am having trouble with classes
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 1f;
public float smoothTime = 0.1f;
private Vector3 velocity = Vector3.zero;
public float PlayerX;
public float PlayerY;
public float PlayerZ;
void Update()
{
// Get input from the player
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
// Create a movement vector based on input
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
// Apply smooth movement
Vector3 targetPosition = transform.position + movement * speed * Time.deltaTime;
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
position();
}
void position()
{
Vector3 position = transform.position;
PlayerX = position.x;
PlayerY = position.y;
PlayerZ = position.z;
}
}
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
PlayerMovement Player = new PlayerMovement();
{
Vector3 CameraPosition = transform.position;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
CameraPosition.x = PlayerX-0.111f;
CameraPosition.y = PlayerY+4.5f;
CameraPosition.z = PlayerZ-3f;
}
}
Don't new() a MonoBehaviour
oh
Either drag and drop (serialized reference), getcomponent, or use a singleton or something to return the instance returned from instantiate
In that order of preference
the code you posted is also not valid c#, full of syntax errors
singleotne
its because
my IDE
doesnt identify errors
The link I sent shows you how. But also, note that I said that is the least preferable
It just acts like an editing and writing tool
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
basicly notepad with collers
Please finish a thought before hitting enter. And follow the instructions that bawsi linked
░ * please * 💀 lmao
Yes...
please just dont slam docs in my face if possible and try to explain quiky through chat
ahh ok
thanks
wauit
buh
u just linked it to the docs
._.
I did not. That is not the docs
ok fine i guess
!warn 798096065949728808 Don't spam on the server read #📖┃code-of-conduct
mlssp166 has been warned.
if it is least preferable
then what should i use instead
I already told you
#archived-code-general message
GetComponent
Is it possible, u just give an example or QUICKLY explain through chat
That is the second one.
I mean its ok, its not ur job anyways
Just "drag and drop" it
Literally that is it
That is the whole explanation
Make a field, drag the component into that field in the inspector
A variable
The box that shows in the inspector when you make a variable that is public or has the attribute [SerializeField]
And I don't think you are dumb. Everyone starts somewhere
You should follow the pathways in !learn.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
@swift falcon Don't spam single word messages. There are tutorials and courses on Unity Learn explaining basics
The inspector is the window that says "inspector" at the top
What is window 😭
Panel, window, not sure the right word.
I dont see no inspectors
It is usually on the right
No. Not that at all
tryna make this camera follow the ball
At this point though, definitely stop and do the learn site I linked above
No no no
@swift falcon Create a thread if you want to continue asking questions covered by basic tutorials
I recommend going through !learn to first understand the basics
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I know enough, its just that i am shifiting from another Game engine
I mean, it would be waaaaay faster than this
I have made lots of complex games before and this is ez
It's the stuff needed to be known from shifting from other languages/engines/frameworks.
I just dont know how to navigate my way through
You don't know the basics. The essentials pathway will get you familiar with the engine very quickly
Essentials is all about just how to navigate unity
I dont hjave time to wathc 750 hours of videos
Fast forward through what you're already aware of but I'm certain if you're asking questions about attributes and the Editor windows, going through the learning process would help significantly.
That is for ALL the material. Essentials can be done in a day
You aren't expected to watch all 750 hours...
Working here as well. And the button was fixed too.
🙃
vpn might have something to do with it
It wokre
it wokerd
@dusk apex@dusk apex@dusk apex@dusk apex@dusk apex
bro can you tell me where i should start, all the first videos seem tooo basic
@swift falcon Go through tutorial, stop spamming the channel.
Hey, idk why but i can't link my button with a function :
(I have a gameobject with the script and its in "OnClick()") ^^
If you're just wanting to get straight to the hands on stuff, probably the "Essentials of real-time 3D"
also
because of List parameter
Where the first step would be working with game objects and scene ect
at least 1
Ohh okay thanks !
Guys can someone quickly just give me an example or video or explain how to access and modify variables and classes from other Classes
@swift falcon You were already provided with the information. #archived-code-general message
Its really weird, i cant click on my button , why ? (when i run ofc)
I did nothing about it
Either you have panel on top of it or event system is not present or active
UI is sorted by order in hierarchy
You are missing the EventSystem...
I'd never needed it before, but I'm sure I'm wrong. Don't worry, I'll fix it. ^^ Thanks !
bro 😭
The ui events won't work without an event system.
It is usually created automatically, so when it worked before, it was likely there and you just didn't see it
Sometimes people accidentally delete it
Yeah you right ahah i'm beginner so sometimes in forgot some thing ^^
It's super common. I have even STILL make that mistake after almost a decade of using unity
It just, for some reason, is not always my first thought when having ui issues
Hello,
When using Jobs, is there a way to chain multiple scheduling when they read/write to the same things?
I thought using the "depends on = JobHandle" parameter was made for this and indicate to wait for the previous Job to be finished, but apparently not since it's throwing errors.
Do I really have to call Complete() between each Jobs or there is a way to do it somehow?
May want to ask in #1062393052863414313
I am not sure though, sorry
Been a while since I used jobs
Will check there then, thanks.
Hello, my unity project is HDRP, i added a gradient sky and i guess the ground terrian has too much reflection, it is way too bright. Do you guys know how to solve this?
good morning, i dont know if this is the best place to ask this, but really is needed to add in the update this? Steamworks.SteamClient.RunCallbacks();, i only will use for some random achievements, but in documentation told us to add this in every frame?
someone helped me! thank you all
I am trying to access varibables of another class and change and edit them Live without creating a duplicate or new Instance Of it in my currect class
how did i mess it up
this should be highlighting errors. your ide likely still isnt configured
meh
the error is here


you really should also step away from unity and just do basic c#. There are many resources out there where you can learn properly
but also getting your ide configured is required for help here
I am cracked at java
so i decided not to learn C#
after all, they are almost the EXACT same thing, plus im doing good so far, i am just having trouble in 1 our of every 300 lines of code i write
Come on man plz help me
c# is java++, so you should learn it
just like you cant say you know c so you know c++